JObject Parse Data with a variable as the value

馋奶兔 提交于 2019-12-13 03:50:00

问题


I am trying to decipher the correct syntax for using JObject Parse when I need to have one of the values set by a variable. This is for using Algolia to push a new object to my search index.

songIndexHelper.PartialUpdateObject(JObject.Parse(@"{""ApprovalFL"":"true",
                        ""objectID"":"'+Accepted.Value+'"}"));

I receive Accepted.Value from my function argument. For example, Accepted.Value could equal something like 98. Also, true should be formatted as boolean instead of a string. The above is my attempt. How should I fix my syntax?

I'm following this documentation from Algolia: https://www.algolia.com/doc/api-reference/api-methods/partial-update-objects/

For more context, here is the above line in the function:

public ActionResult Index(int? Accepted, int? Denied)
{
    var accountInfo = EntityDataAccess.GetAccountInfoByUserID(User.Identity.GetUserId());
    if(accountInfo == null || accountInfo.AdminFL == false || accountInfo.LabelFL == true)
    {
        return RedirectToAction("Index", "Home");
    }
    else
    {
        if(Accepted != null)
        {
            EntityDataAccess.AcceptSong(Accepted.Value);
            var songIndexHelper = HttpContext.Application.Get("SongIndexHelper") as IndexHelper<SongAlgoliaModel>;
            songIndexHelper.PartialUpdateObject(JObject.Parse(@"{""ApprovalFL"":""true"",
                                    ""objectID"":""Accepted.Value""}"));
        }

回答1:


songIndexHelper.PartialUpdateObject(JObject.Parse(@"{""ApprovalFL"":""true"",
                                ""objectID"":""Accepted.Value""}"));

should be:

songIndexHelper.PartialUpdateObject(JObject.Parse(@"{""ApprovalFL"":true,
    ""objectID"":" +Accepted.Value+ "}"));

The key is to use + to concatenate in the value of Accepted, and not wrap true in quotes.

Another approach I would suggest is not using strings at all. Consider an approach like:

var bob = new { ApprovalFL = true, objectID = Accepted.Value};
var obj = JObject.FromObject(bob);
songIndexHelper.PartialUpdateObject(obj);



回答2:


This should produce what you are looking for:

String json = "{\"ApprovalFL\":true,\"objectID\":" + Accepted.Value.ToString() + "}";

which is:

{"ApprovalFL":true,"objectID":98}


来源:https://stackoverflow.com/questions/47859145/jobject-parse-data-with-a-variable-as-the-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!