4

I've got a json array that I want to add to, then write the content to a file. I have no problem adding the content to the array, but writing to file using the JsonSerializer.Serialize method gives me the exception:

ArgumentException: Can not add Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JObject.

This occurs on the last line of my code below. "jSerializer.Serialize(o.CreateWriter(), o);"

JSON

{
"ArrayToManipulate":
[
    {
        "Name":"Value"
    },
    {
        "Name":"value"
    }
]
}

Code to manipulate the JSON Objects

JContainer o = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
JArray x = (JArray)o["ArrayToManipulate"];
ContentObject newObject = new ContentObject(){Name="Value"};
JToken tokenToAdd = JToken.Parse(JsonConvert.SerializeObject(newObject, Formatting.Indented));
x.Add(tokenToAdd);
JsonSerializer jSerializer = new JsonSerializer();
jSerializer.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
jSerializer.Serialize(o.CreateWriter(), o);

Am I going about this the wrong way?

1 Answer 1

1

The writer you get by calling JContainer.CreateWriter doesn't write to a file as you want - it is a writer to write to the container itself. You need something like the code below - create a "regular" text writer based on a file, then a JsonWriter based on that.

const string JSON = "{\"ArrayToManipulate\":[{\"Name\":\"Value\"},{\"Name\":\"value\"}]}";
var reader = new StringReader(JSON);
JContainer o = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
JArray x = (JArray)o["ArrayToManipulate"];
ContentObject newObject = new ContentObject() { Name = "Value" };
JToken tokenToAdd = JToken.Parse(JsonConvert.SerializeObject(newObject, Formatting.Indented));
x.Add(tokenToAdd);
JsonSerializer jSerializer = new JsonSerializer();
jSerializer.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
using (var w = File.CreateText(@"C:\temp\a.json"))
{
    using (var jw = new JsonTextWriter(w))
    {
        jSerializer.Serialize(jw, o);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

And how **DE-Serialize" from a a.json file ?

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.