反序列化包含键和值关键字的Json

时间:2019-07-17 22:43:49

标签: c# json serialization

我有一个看起来像这样的Json:

{
 "Title:": "StructureTitle",
 "Description:" : "StructureDescription",
 "Contents": "[{"Key":"FirstKey","Value":"FirstValue"},{"Key":"SecondKey","Value":"SecondValue"},{"Key":"ThirdKey","Value":"ThirdValue"}]"
}

而且我无法弄清楚如何对其进行反序列化,因为“内容”部分指定了什么是键,什么是值。

我已经用这种方式定义了我的班级

    public class Info
    {
       public string Title{ get; set; }
       public string Description{ get; set; }
       public Contents Contents{ get; set; }
    }


    [DataContract]
    public class Contents {

        [DataMember(Name = "FirstKey")]
        public string FirstKey{ get; set; }

        [DataMember(Name = "SecondKey")]
        public string SecondKey{ get; set; }

        [DataMember(Name = "ThirdKey"]
        public string ThirdKey { get; set; }

     }

我正在尝试以这种方式执行反序列化:

var text = "{ "Title:": "StructureTitle", "Description:" : "StructureDescription", "Contents": "[{"Key":"FirstKey","Value":"FirstValue"},{"Key":"SecondKey","Value":"SecondValue"},{"Key":"ThirdKey","Value":"ThirdValue"}]" }"
JToken token = JObject.Parse(text);
var x = token.SelectToken("Contents");
Contents c = x.ToObject<Contents>();

这是我得到的错误: Newtonsoft.Json.JsonSerializationException:'转换值时出错

1 个答案:

答案 0 :(得分:0)

var text = "{ \"Title: \": \"StructureTitle\", \"Description: \" : \"StructureDescription\", \"Contents\": [{ \"Key\":\"FirstKey\",\"Value\":\"FirstValue\"},{ \"Key\":\"SecondKey\",\"Value\":\"SecondValue\"},{ \"Key\":\"ThirdKey\",\"Value\":\"ThirdValue\"}] }";
JToken token = JObject.Parse(text);
var x = token.SelectToken("Contents");
Contents c = x.ToObject<Contents>();