我正在尝试将一串JSON数据转换为C#类对象。然而,我对JSON的一小部分有一个问题,它本质上是动态的。
JSON的部分如下:
"contact": [{
"comment": null,
"type": {
"id": "cell",
"name": "Example name"
},
"preferred": true,
"value": {
"country": "7",
"formatted": "+7 (702) 344-3423-3",
"number": "3498908",
"city": "702"
}
},
{
"type": {
"id": "email",
"name": "Email example"
},
"preferred": false,
"value": "name@mail.com"
}]C#类
public class Value
{
public string country { get; set; }
public string formatted { get; set; }
public string number { get; set; }
public string city { get; set; }
}
public class Type
{
public string id { get; set; }
public string name { get; set; }
}
public class Contact
{
public string comment { get; set; }
public Type type { get; set; }
public bool preferred { get; set; }
public string value { get; set; }
}C#码
Contact contact = JsonConvert.DeserializeObject<Contact>(result);“值”的格式取决于联系人信息。是否可以将值同时映射为字符串和类值。
谢谢你能提供的任何帮助。
发布于 2017-06-22 10:23:25
您可以直接使用dynamic,即
public dynamic value { get; set; }如果它看起来像一个对象,它将被具体化为一个JObject,它可以通过dynamic API使用,所以.value.country将工作,等等。如果它看起来像一个整数,bool或字符串:它将被物化为这样。数组也将得到适当的处理。所以:您可以检查.value is string等。请注意,这不会使用您的Value类型,这样做要复杂得多,但是: meh;您将得到数据。你总可以手动把它换掉。
如果您使用object而不是dynamic,那么它的行为也会是这样,但是访问内部属性就更困难了。
发布于 2017-06-22 10:21:24
试一试
Contact contact = JsonConvert.DeserializeObject<Contact>(result[0]);正如您在JSON中所看到的,它是
"contact": [指示数组,当前您只是传递整个数组
发布于 2017-06-22 10:28:23
除非您确信JSON总是具有相同的结构,最好是在类中使用dynamic变量而不是deserialize变量。
如果您喜欢使用类,则始终可以使用runtime使用reflection构建自己的类。但这就像用加农炮杀死苍蝇一样,您可能不需要它,所以只需使用dynamic变量,这是最好的处理JSON字符串的方法。
https://stackoverflow.com/questions/44696494
复制相似问题