3

I'm trying to make use of Netwonsoft.JSON.Linq in C#, to change the "statusCode" values in the following JSON:

{  
   "disbursements":[  
      {  
         "id":"1f337641",
         "contactId":"f5eb2",
         "statusCode":166000005,
         "amount":8,
         "category":166000001
      },
      {  
         "id":"027a4762",
         "contactId":"f5eb2038",
         "statusCode":166000000,
         "amount":4000,
         "category":166000000
      }
   ]
}

So, inside the JSON data is: "disbursements" which is JSON array. I have to change the "statusCode" of each item in the array to 166000005. I'm able to retrieve statusCode of the first one using

JObject jsonText = JObject.Parse(bodyText);
var statusCode = (int)jsonText.SelectToken("disbursements[0].statusCode");

But I need a solution with loop or LINQ that changes all the values, not just the first.

4
  • 1
    1) Could you please edit your question to provide a valid JSON sample? Your current JSON fails validation at jsonlint.com. Maybe you just need outer braces { and }? 2) You wrote, I'm able to retrive statusCode by 'disbursement[0]["statCode"]'. Can you show what you tried and why it doesn't work, so we don't have to guess and provide an answer you don't need? See How to Ask. Commented Sep 14, 2017 at 20:23
  • This isn't valid JSON but why cant you just loop over your object Newtonsoft deserialized for you? Commented Sep 14, 2017 at 20:24
  • Is this what you want? Replace Part of a Json with Other (using a string token) C# , Json.Net. Commented Sep 14, 2017 at 20:28
  • I want to just change statusCode value to '166000008' Commented Sep 14, 2017 at 21:25

2 Answers 2

7

The following code sets or adds "statusCode": 166000005 to every entry in the disbursement array:

var jsonText = JObject.Parse(bodyText);
foreach (var disbursement in jsonText.SelectTokens("disbursements[*]"))
{
    disbursement["statusCode"] = 166000005;
}

Notes:

  • The query string "disbursements[*]" contains the JSONPath wildcard operator [*]. This operator matches all array elements under the parent element "disbursement".

    Json.NET supports JSONPath syntax as documented in Querying JSON with JSONPath.

  • SelectTokens() is used rather than SelectToken() to loop through multiple possible matches.

  • The JToken item setter disbursement["statusCode"] = 166000005 will replace the "statusCode" property if present and add it if not.

  • A simple, atomic value such as 166000005 can be set directly into a JToken hierarchy. For a complex POCO you would need to call JToken.FromObject() to serialize it to a JToken before setting it in the hierarchy, e.g.:

    disbursement["statusCode"] = 
        JToken.FromObject( new { oldValue = disbursement["statusCode"], newValue = 166000005 } );
    

Sample working .Net fiddle.

Sign up to request clarification or add additional context in comments.

Comments

0

I would create classes to represent the data. Here is my solution:

Create the data holder classes:

public class Disbursement
{
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("contactId")]
    public string ContactId { get; set; }

    [JsonProperty("statusCode")]
    public int StatusCode { get; set; }

    [JsonProperty("amount")]
    public int Amount { get; set; }

    [JsonProperty("category")]
    public int Category { get; set; }
}

The collection:

public class Disbursements
{
    [JsonProperty("disbursements")]
    public List<Disbursement> Items { get; set; } = new List<Disbursement>();
}

And then the loading / modifying / saving data:

class Program
{
    static void Main(string[] args)
    {
        var disbursements =
            JsonConvert.DeserializeObject<Disbursements>(
                File.ReadAllText(
                    "data.json",
                    Encoding.UTF8
                )
            );

        foreach (var disbursement in disbursements.Items)
        {
            disbursement.StatusCode = 166000005;
        }

        string modifiedContent = JsonConvert.SerializeObject(disbursements);

        File.WriteAllText(
            "modifiedData.json",
            modifiedContent,
            Encoding.UTF8
        );
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.