Search code examples
c#jsonunity-game-enginejson.netlitjson

Convert LitJson to Newtonsoft Json for run at IOS device Unity C#


How to convert the LitJson Json To NewtonSoft Json in unity c# ?

Example :

In LitJson

JsonData CJsonData;
cJsonData = JsonMapper.ToObject(www.downloadHandler.text);
Debug.log(cJsonData["reason"].ToString();

// This cJsonData can contain a nested array.

How the code look like in a Newtonsoft Json for ios ?

I dont want to create a class property because the return from www.donwloadHandler.text could be different. It is depend on the return. When using LitJson with datatype JsonData and use JsonMapper.Tobject i could easily get the data without need any more code.

*

In LitJson we have DataType JsonData which is automatic convert it to an associated array from Mapper.

*

I want i can get the data like LitJson

Debug.log(cJsonData["reason"].ToString();

Or Maybe

Debug.log(cJsonData["reason"]["abc"].ToString();

Or Maybe

Debug.log(cJsonData["reason"]["cc"]["aaa"].ToString();

But in newtonsoft json we must add a class to deserializeobject.

In newtonsoft json :

someclass Json = JsonConvert.DeserializeObject<someclass>(www.donwloadHandler.text);

This i dont want. Because we need to add someclass

and this :

string data = JsonConvert.DeserializeObject(www.downloadHanlder.text);

This also i dont want. Because it is string not an associated array like litjson.

Is that clear ?

Thank You


Solution

  • It's much the same. No need to deserialise to read the data, just use a JObject:

    using System;
    using Newtonsoft.Json.Linq;
    
    public class Program
    {
        public static void Main()
        {
            string json = @"
                {
                  ""CPU"": ""Intel"",
                  ""Integrated Graphics"": true,
                  ""USB Ports"": 6,
                  ""OS Version"": 7.1,
                  ""Drives"": [
                    ""DVD read/writer"",
                    ""500 gigabyte hard drive""
                  ],
                  ""ExtraData"" : {""Type"": ""Mighty""}
                }";
    
            JObject o = JObject.Parse(json);
    
            Console.WriteLine(o["CPU"]);
            Console.WriteLine();
            Console.WriteLine(o["Drives"]);
            Console.WriteLine();
            Console.WriteLine(o["ExtraData"]["Type"]);
    
            Console.ReadLine();
        }
    }