首页 > 解决方案 > 将 LitJson 转换为 Newtonsoft Json 以在 IOS 设备 Unity C# 上运行

问题描述

如何在统一 c# 中将 LitJson Json 转换为 NewtonSoft Json?

例子 :

在利特森

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

// 这个 cJsonData 可以包含一个嵌套数组。

ios 的 Newtonsoft Json 中的代码如何?

我不想创建类属性,因为 www.donwloadHandler.text 的返回可能不同。这取决于回报。当使用具有数据类型 JsonData 的 LitJson 并使用 JsonMapper.Tobject 时,我可以轻松获取数据而无需更多代码。

*

在 LitJson 中,我们有 DataType JsonData,它会自动将其转换为来自 Mapper 的关联数组。

*

我希望我能得到像 LitJson 这样的数据

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

或者可能

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

或者可能

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

但是在 newtonsoft json 中,我们必须添加一个类来反序列化对象。

在 newtonsoft json 中:

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

这是我不想要的。因为我们需要添加一些类

和这个 :

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

这也是我不想要的。因为它是字符串而不是像 litjson 这样的关联数组。

明白了吗 ?

谢谢你

标签: c#jsonunity3djson.netlitjson

解决方案


这几乎是一样的。无需反序列化即可读取数据,只需使用 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();
    }
}

推荐阅读