JObject Parse Data with a variable as the value

2019-08-24 02:37发布

问题:

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}