【问题标题】:Deserialization JSON string with JSON.NET使用 JSON.NET 反序列化 JSON 字符串
【发布时间】:2010-11-13 18:04:04
【问题描述】:

无奈,需要反序列化这种格式的JSON字符串来上课。

JSON 字符串:

{
  "newNickInfo": {
    "2775040": {
      "idUser": 2775040,
      "nick": "minci88",
      "sefNick": "minci88",
      "sex": 2,
      "photon": "http:\/\/213.215.107.125\/fotky\/277\/50\/n_2775040.jpg?v=4",
      "photos": "http:\/\/213.215.107.125\/fotky\/277\/50\/s_2775040.jpg?v=4",
      "logged": false,
      "idChat": 0,
      "roomName": "",
      "updated": 1289670130
    }
  }
}

类:

public class User 
{
    public string idUser { get; set; }
    public string nick { get; set; }
    public string sefNick { get; set; }
    public string sex { get; set; }
    public string photon { get; set; }
    public string photos { get; set; }
    public bool logged { get; set; }
    public int idChat { get; set; }
    public string roomName { get; set; }
    public string updated { get; set; }
}

第一个问题是,类属性必须小写,第二个问题是我尝试了很多方法,但我不知道如何从这个json字符串中剪切json对象并在类中反序列化。 有什么想法吗?感谢您的帮助。

还有一个问题,如果我想把这个json字符串反序列化成什么格式的c#类。

【问题讨论】:

  • 你尝试了哪些方法,得到了什么结果?

标签: c# json json.net deserialization


【解决方案1】:

看起来您的 JSON 字符串不正确。看看这个

string json = @"[

    {
      "newNickInfo": "2775040", 
      "idUser": "2775040",
      "nick":"minci88",
      "sefNick":"minci88",
      "sex":2,
      "photon":"http:\/\/213.215.107.125\/fotky\/277\/50\/n_2775040.jpg?v=4",
      "photos":"http:\/\/213.215.107.125\/fotky\/277\/50\/s_2775040.jpg?v=4",
      "logged":false,
      "idChat":0,
      "roomName":"",
      "updated":"1289670130"
     }
]";



public class User 
{
[JsonProperty] 
public string idUser{get;set;}
[JsonProperty] 
public string nick{get;set;}
[JsonProperty] 
public string sefNick{get;set;}
[JsonProperty] 
public string sex{get;set;}
[JsonProperty] 
public string photon{get;set;}
[JsonProperty] 
public string photos{get;set;}
[JsonProperty] 
public bool logged{get;set;}
[JsonProperty] 
public int idChat{get;set;}
[JsonProperty] 
public string roomName{get;set;}
[JsonProperty] 
public string updated{get;set;} 
}


List<User> users = JsonConvert.DeserializeObject<List<User>>(json);

User u1 = users[0];

Console.WriteLine(u1.nick);

【讨论】:

    【解决方案2】:
    using System.Web.Script.Serialization;
    
    var serializer = new JavaScriptSerializer();
    var deserialized = serializer.Deserialize<Dictionary<string, Dictionary<string, User>>>(theJsonString);
    var theUser = deserialized["newNickInfo"]["2775040"];
    

    【讨论】:

    • 您好 Domenic,您的解决方案不起作用。试试看,我得到编译错误: System.Collections.Generic.Dictionary>' is a 'type' but is used like a 'variable'
    • 是的,我忘了结束&gt;;立即尝试。
    【解决方案3】:

    我使用这个工具Jsonclassgenerator。它可以为输入的 Json 字符串生成 C# 类。您不必使用生成的确切类。但是你可以看到类的格式并在你的项目中创建一个类似的。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多