我有一个我要添加的json数组,然后将内容写入文件.我没有问题将内容添加到数组,但使用JsonSerializer.Serialize方法写入文件给了我例外:
ArgumentException的:
无法将Newtonsoft.Json.Linq.JObject添加到Newtonsoft.Json.Linq.JObject.
这发生在我下面的代码的最后一行. “jSerializer.Serialize(o.CreateWriter(),o);”
{ "ArrayToManipulate": [ { "Name":"Value" },{ "Name":"value" } ] }
用于操作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()); jSerializer.Serialize(o.CreateWriter(),o);
我是以错误的方式来做这件事的吗?
解决方法
通过调用JContainer.CreateWriter获得的编写器不会根据需要写入文件 – 它是写入容器本身的编写器.您需要类似下面的代码 – 基于文件创建“常规”文本编写器,然后基于该文件创建JsonWriter.
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); } }