使用LINQ创建JSON的异常 [英] Exception creating JSON with LINQ

查看:87
本文介绍了使用LINQ创建JSON的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码创建JSON:

I am trying to create JSON with the following code:

        JArray jInner = new JArray("document");
        JProperty jTitle = new JProperty("title", category);
        JProperty jDescription = new JProperty("description", "this is the description");
        JProperty jContent = new JProperty("content", content);
        jInner.Add(jTitle);
        jInner.Add(jDescription);
        jInner.Add(jContent);

当我进入jInner.Add(jTitle)时,出现以下异常:

when I get to the jInner.Add(jTitle), I get the following exception:

System.ArgumentException: Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray.
   at Newtonsoft.Json.Linq.JContainer.ValidateToken(JToken o, JToken existing)
   at Newtonsoft.Json.Linq.JContainer.InsertItem(Int32 index, JToken item, Boolean skipParentCheck)
   at Newtonsoft.Json.Linq.JContainer.AddInternal(Int32 index, Object content, Boolean skipParentCheck)

有人可以帮我告诉我我在做什么错吗?

Can anybody help and tell me what am I doing wrong?

推荐答案

向数组添加属性没有意义.数组由值组成,而不是键/值对.

It doesn't make sense to add a property to an array. An array consists of values, not key/value pairs.

如果您想要这样的东西:

If you want something like this:

[ {
  "title": "foo",
  "description": "bar"
} ]

那么您只需要一个中间JObject:

then you just need an intermediate JObject:

JArray jInner = new JArray();
JObject container = new JObject();
JProperty jTitle = new JProperty("title", category);
JProperty jDescription = new JProperty("description", "this is the description");
JProperty jContent = new JProperty("content", content);
container.Add(jTitle);
container.Add(jDescription);
container.Add(jContent);
jInner.Add(container);

请注意,我也从JArray构造函数调用中删除了"document"参数.目前尚不清楚您为什么拥有它,但我强烈怀疑您不想要它. (这会使数组的第一个元素成为字符串"document",这很奇怪.)

Note that I've removed the "document" argument from the JArray constructor call too. It's not clear why you had it, but I strongly suspect you don't want it. (It would have made the first element of the array the string "document", which would be fairly odd.)

这篇关于使用LINQ创建JSON的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆