1

I am trying to change the JSON from a JSON file so I can run it to get a JSON response, I found the code on this post: Change values in JSON file (writing files) can anyone fix this?

Error:

An unhandled exception of type 'System.ArgumentException' occurred in Newtonsoft.Json.dll

Additional information: Set JArray values with invalid key value: "filter". Int32 array index expected.

JSON:

[{
  "tablename" : "table",
  "columns" : "id, name",
  "filter" : "id = 10"
}] 

Code:

string json = File.ReadAllText("file.json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
jsonObj["filter"] = "id = 20";
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("file.json", output);

(The JSON is made to talk to a webservice)

Community
  • 1
  • 1
sansactions
  • 215
  • 5
  • 17

2 Answers2

2

I believe this should be:

jsonObj[0]["filter"] = "id = 20";

As your JSON is an array. So 0 is the first object in the array.

Andrew Monks
  • 656
  • 4
  • 11
1

You have a few options but seeing as you deserialize it to a dynamic then you can try the following.

var json = File.ReadAllText("file.json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

jsonObj[0].filter = "id = 20"; //<--CALLING PROPERTY DIRECTLY via DynamicObject

var output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("file.json", output);

The JSON data shown is a JSON array so you need to use index to get elements of the array.

You could also create a class to hold the deserialized data

public class Model
{
    public string tablename { get; set; }
    public string columns { get; set; }
    public string filter { get; set; }
}

and use that

var json = File.ReadAllText("file.json");
//Deserializing Object to Model Array
var jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject<Model[]>(json);

jsonObj[0].filter = "id = 20"; //<--CALLING PROPERTY DIRECTLY

var output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("file.json", output);
Nkosi
  • 235,767
  • 35
  • 427
  • 472