2

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?

4
  • 1
    In your second sample it should be nickname.api_data.api_basic.api_nickname Commented Sep 2, 2016 at 14:34
  • 1
    Your JSON is not valid. Remove the comma after "api_nickname": "David" Commented Sep 2, 2016 at 14:35
  • 1
    What do you mean by doesn't work ? Does it throw a runtime exception? Does it not compile? Please be more clear and specific Commented Sep 2, 2016 at 14:36
  • omg, you solve my problem extremely quick. thank you Ulugbek Umirov Ferhat Sayan, Matias Cicero, Alberto Commented Sep 2, 2016 at 14:44

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.