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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Gopinath
  • 95
  • 3
  • 7
  • 1
    1) Could you please [edit] your question to provide a valid JSON sample? Your current JSON fails validation at https://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 [ask]. – dbc Sep 14 '17 at 20:23
  • This isn't valid JSON but why cant you just loop over your object Newtonsoft deserialized for you? – Sam Marion Sep 14 '17 at 20:24
  • Is this what you want? [Replace Part of a Json with Other (using a string token) C# , Json.Net](https://stackoverflow.com/a/33056210/3744182). – dbc Sep 14 '17 at 20:28
  • I want to just change statusCode value to '166000008' – Gopinath Sep 14 '17 at 21:25

2 Answers2

5

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.

dbc
  • 104,963
  • 20
  • 228
  • 340
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
        );
    }
}
Gabor
  • 3,021
  • 1
  • 11
  • 20