A. Chung A. Chung - 3 months ago 10
JSON Question

C#: Deserialize JSON

I have a problem with Deserializing JSON

This is my JSON file

{
"api_result": 1,
"api_result_msg": "OK",
"api_data": {
"api_basic": {
"api_nickname": "David",
},
"api_p_bgm_id": 112,
"api_parallel_quest_count": 5
}
}


The matching class(generated by special paste in 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; }
}


And my code:

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);


The output:

result:OK <---success
nickname: <---fail


I tried:

Rootobject nickname = JsonConvert.DeserializeObject<Rootobject>(JJ);
Console.WriteLine(nickname.api_basic.api_nickname);


But this doesn't work.

What am I doing wrong?

Answer

Why performing the deserialization two times?

You only need the first object:

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);