【问题标题】:Convert LitJson to Newtonsoft Json for run at IOS device Unity C#将 LitJson 转换为 Newtonsoft Json 以在 IOS 设备 Unity C# 上运行
【发布时间】:2019-09-25 16:41:44
【问题描述】:

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

例子:

在 LitJson 中

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

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

代码在 Newtonsoft Json for ios 中的外观如何?

我不想创建类属性,因为 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 这样的关联数组。

清楚吗?

谢谢

【问题讨论】:

  • 我不完全确定你在追求什么。这只是询问如何使用 newtonsoft 获取 json 字段吗?
  • @Ben 我想要上面的 litjson 示例中的 newtonsoft json 得到相同的结果吗?代码在 newtonsoft json 中的样子?
  • @Ben 请再看一遍这个问题。我已经用更详细的解释编辑了这个问题。

标签: c# json unity3d json.net litjson


【解决方案1】:

大同小异。无需反序列化即可读取数据,只需使用 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();
    }
}

【讨论】:

    猜你喜欢
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多