Search code examples
c#jsonunity-game-enginemonodevelop

How to read a JSON response in Unity?


I am new to Unity and I have been trying read the JSON response from my RESTful API using C#. Here's what I've tried with LitJson:

JsonData jsonvale = JsonMapper.ToObject(www.text);

string parsejson;
parsejson = jsonvale["myapiresult"].ToString();

My JSON response is {"myapiresult":"successfull"}

For whatever reason, it doesn't work currently. I don't know how to fix it.

I also found a paid plugin for JSON.NET but I'm not sure if it will solve my problem.


Solution

  • You don't need to buy any paid plugins to use JSON.NET here. You can either create a class that models the response or deserialize to a dynamic object.

    Example of the former:

    using Newtonsoft.Json;
    // ...
    class Response
    {
        [JsonProperty(PropertyName = "myapiresult")]
        public string ApiResult { get; set; }
    }
    
    void Main()
    {
        string responseJson = "{\"myapiresult\":\"successfull\"}";
        Response response = JsonConvert.DeserializeObject<Response>(responseJson);
        Console.WriteLine(response.ApiResult);
        // Output: successfull
    }
    

    ...and the latter:

    using Newtonsoft.Json;
    // ...
    void Main()
    {
        string responseJson = "{\"myapiresult\":\"successfull\"}";
        dynamic response = JsonConvert.DeserializeObject(responseJson);
        Console.WriteLine(response.myapiresult.ToString());
        // Output: successfull
    }