[英]deserializing JSON to .net object
我在將JSON反序列化為對象時遇到問題。 我讀了幾個答案,但沒有一個對我有幫助。
這是我的JSON文件:
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"blog": {
"title": "title",
"name": "name",
"url": "url"
}
}
}
這是我的課:
public class TextInfo
{
public class Meta
{
public int status { get; set; }
public string msg { get; set; }
}
public class Blog
{
public string title { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Response
{
public Blog blog { get; set; }
}
public class RootObject
{
public Meta meta { get; set; }
public Response response { get; set; }
}
}
現在,我嘗試像這樣反序列化json,但是我不知道如何操作數據:
TextInfo txt = JsonConvert.DeserializeObject<TextInfo>(json);
你能幫我解決這個問題嗎? 提前致謝。
唯一的區別是TextInfo應該包含Meta和Response:
public class TextInfo
{
public Meta meta { get; set; }
public Response response { get; set; }
}
public class Meta
{
public int status { get; set; }
public string msg { get; set; }
}
public class Blog
{
public string title { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Response
{
public Blog blog { get; set; }
}
然后像您說的那樣反序列化:
TextInfo txt = JsonConvert.DeserializeObject<TextInfo>(json);
三件事:
您能否提供錯誤消息/日志,
您只解析一項還是多項? 在第二種情況下: var txt = JsonConvert.DeserializeObject<List<TextInfo>>(JSONstr);
請嘗試以下操作:
public class Meta { public int status { get; set; } public string msg { get; set; } } public class Response { public Blog blog { get; set; } } public class Blog { public string title { get; set; } public string name { get; set; } public string url { get; set; } } public class TextInfo { public Meta meta { get; set; } public Response response { get; set; } }
您的TextInfo
類內部沒有任何要反序列化的屬性。 它僅聲明另一個類。 根據您的消息來源,您應該反序列化為RootObject
。 這將返回具有meta
和response
屬性的實例。 然后,您將訪問它們:
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(obj.meta.msg);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.