Json在C#中使用Newtonsoft.Json - 对象序列化为Property。期望JObject实例

时间:2016-10-27 12:24:54

标签: c# json

我收到错误“Object serialized to Property.JObject instance expected。”尝试使用以下内容时:

        SortedList<string,string> results = new SortedList<string,string>();
        results.Add("BOBB", "Bob Brattwurst");
        results.Add("DANG", "Dan Germany");
        results.Add("KON", "Konrad Plith");

        JObject output = JObject.FromObject(
            new JProperty("suggestions",
                new JArray(
                    from r in results
                    orderby r.Value
                    select new JObject(
                        new JProperty("value", r.Key),
                        new JProperty("data", r.Value)
                        )
                )
            )
        );

设置输出变量时发生错误。

这是放在Web服务中的,预期的Json结果应如下所示:

{
"suggestions": [
    { "value": "BOBB", "data": "Bob Brattwurst" },
    { "value": "DANG", "data": "Dan Germany" },
    { "value": "KON",  "data": "Konraid Plith" }
]
}

我查看了一个我在这里找到的例子:http://www.newtonsoft.com/json/help/html/CreatingLINQtoJSON.htm 但是我不太明白这个问题。

2 个答案:

答案 0 :(得分:2)

您可以将数据读入自定义数据结构(如果您愿意,也可以是匿名类型),它代表您的json:

public class JsonContainer
{
    [JsonProperty("suggestions")]
    public List<JsonData> Suggestions { get;set; }
}

public class JsonData
{
    [JsonProperty("value")]
    public string Value { get; set; }

    [JsonProperty("data")]
    public string Data { get; set; }
}


// ...

var results = new SortedList<string, string>();
results.Add("BOBB", "Bob Brattwurst");
results.Add("DANG", "Dan Germany");
results.Add("KON", "Konrad Plith");

var container = new JsonDataContainer();
container.Suggestions = results.Select(r => new JsonData
{
    Value = r.Key,
    Data = r.Value
}).ToList();

var json = JsonConvert.SerializeObject(container);

答案 1 :(得分:1)

一种解决方案可能是将数据读入一个非常糟糕的物体,与heinzbeinz类似。

SortedList<string, string> results = new SortedList<string, string>();
        results.Add("BOBB", "Bob Brattwurst");
        results.Add("DANG", "Dan Germany");
        results.Add("KON", "Konrad Plith");

var obj = new
{
    Suggestions = results.Select(x => new { Value = x.Key, Data = x.Value }).ToList()
};

var jsonString = JsonConvert.SerializeObject(obj);