簡體   English   中英

使用 JSON.NET 反序列化 JSON 字符串

[英]Deserialization JSON string with JSON.NET

我很無奈,我需要將這種格式的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# 類會有什么格式。

看起來您的 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);
using System.Web.Script.Serialization;

var serializer = new JavaScriptSerializer();
var deserialized = serializer.Deserialize<Dictionary<string, Dictionary<string, User>>>(theJsonString);
var theUser = deserialized["newNickInfo"]["2775040"];

我使用這個工具Jsonclassgenerator 它可以為輸入的 Json 字符串生成 C# 類。 您不必使用生成的確切類。 但是你可以看到類的格式並在你的項目中創建一個類似的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM