2

My JSON config.json:

[  
   {  
      "names":"Steam",
      "count": 1,
   },
   {  
      "names":"game",
      "count": 2,
   }
]

I need to update count's property in the array in c#. I tried

JObject objectproperty = JObject.Parse(File.ReadAllText(@"config.json"));

but this gives me the error

Newtonsoft.Json.JsonReaderException: "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1."
3
  • 1
    That's not a valid json object Commented Jun 30, 2018 at 23:42
  • 2
    The exception message tells you the solution. Use JArray for arrays, not JObject (which is, obviously, for objects) Commented Jun 30, 2018 at 23:56
  • I misstiped Mardoxx. Anyways this wasn't my problem in the first place Commented Jul 1, 2018 at 11:31

1 Answer 1

2

You can use a JToken
Assuming that your JSON is:
(notice I had to remove some ,)

[  
   {  
      "names":"Steam",
      "count": 1
   },
   {  
      "names":"game",
      "count": 2
   }
]

You can use this:

var config_file = @"config.json";

var objectproperty = JToken.Parse(File.ReadAllText(config_file));
foreach (var obj in objectproperty)
{
    var count = (long)obj["count"];

    obj["count"] = count * 3;
}

System.IO.File.WriteAllText(config_file, objectproperty.ToString());
Sign up to request clarification or add additional context in comments.

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.