JSON.NET Adding to JArray



我有一个json数组,我想添加到其中,然后将内容写入文件。将内容添加到数组中没有问题,但使用JsonSerializer.Serialize方法写入文件时会出现异常:

ArgumentException:无法将Newtonsoft.Json.Linq.JObject添加到NewtonsoftJson.Lin.JObject.

这发生在我下面代码的最后一行。"jSerializer.Serialize(o.CreateWriter(),o);"

JSON-

{
"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:tempa.json"))
{
    using (var jw = new JsonTextWriter(w))
    {
        jSerializer.Serialize(jw, o);
    }
}

相关内容

  • 没有找到相关文章

最新更新