我有一个问题与反序列化JSON
这是我的JSON文件{
"api_result": 1,
"api_result_msg": "OK",
"api_data": {
"api_basic": {
"api_nickname": "David",
},
"api_p_bgm_id": 112,
"api_parallel_quest_count": 5
}
}
匹配类(在visual studio中通过特殊粘贴生成):
public class Rootobject
{
public int api_result { get; set; }
public string api_result_msg { get; set; }
public Api_Data api_data { get; set; }
}
public class Api_Data
{
public Api_Basic api_basic { get; set; }
public int api_p_bgm_id { get; set; }
public int api_parallel_quest_count { get; set; }
}
public class Api_Basic
{
public string api_nickname { get; set; }
}
和我的代码:
string JJ = "{"api_result":1,"api_result_msg":"OK","api_data":{"api_basic":{"api_nickname":"David"},"api_p_bgm_id":112,"api_parallel_quest_count":5}}";
Rootobject result = JsonConvert.DeserializeObject<Rootobject>(JJ);
Api_Basic nickname = JsonConvert.DeserializeObject<Api_Basic>(JJ);
Console.WriteLine("result:" + result.api_result_msg);
Console.WriteLine("nickname:" + nickname.api_nickname);
输出:result:OK <---success
nickname: <---fail
我试着:
Rootobject nickname = JsonConvert.DeserializeObject<Rootobject>(JJ);
Console.WriteLine(nickname.api_basic.api_nickname);
但是这行不通。
我做错了什么?
为什么要执行两次反序列化?
你只需要第一个对象:
string JJ = "{"api_result":1,"api_result_msg":"OK","api_data":{"api_basic":{"api_nickname":"David"},"api_p_bgm_id":112,"api_parallel_quest_count":5}}";
Rootobject result = JsonConvert.DeserializeObject<Rootobject>(JJ);
Console.WriteLine("result:" + result.api_result_msg);
Console.WriteLine("nickname:" + result.api_data.api_basic.api_nickname);