关于c#:在Unity中对Json和Json数组进行序列化和反序列化

Serialize and Deserialize Json and Json Array in Unity

我有一个使用WWW从PHP文件发送到统一文件的项目列表。

WWW.text看起来像:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[
    {
       "playerId":"1",
       "playerLoc":"Powai"
    },
    {
       "playerId":"2",
       "playerLoc":"Andheri"
    },
    {
       "playerId":"3",
       "playerLoc":"Churchgate"
    }
]

我在哪里修剪string中多余的[]。当我尝试使用Boomlagoon.JSON解析它时,仅检索第一个对象。我发现我必须deserialize()该列表并导入了MiniJSON。

但是我很困惑如何deserialize()这个列表。我想遍历每个JSON对象并检索数据。

如何在Unity中使用C#做到这一点?

我正在使用的班级是

1
2
3
4
5
6
public class player
{
    public string playerId { get; set; }
    public string playerLoc { get; set; }
    public string playerNick { get; set; }
}

修剪[]之后,我可以使用MiniJSON解析json。但是它仅返回第一个KeyValuePair

1
2
3
4
5
6
IDictionary<string, object> players = Json.Deserialize(serviceData) as IDictionary<string, object>;

foreach (KeyValuePair<string, object> kvp in players)
{
    Debug.Log(string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value));
}

谢谢!


Unity在5.3.3更新后将JsonUtility添加到其API中。除非您正在做更复杂的事情,否则请不要理会所有第三方库。 JsonUtility比其他Json库更快。更新到Unity 5.3.3版本或更高版本,然后尝试以下解决方案。

JsonUtility是轻量级的API。仅支持简单类型。它不支持诸如Dictionary之类的集合。 List是一个例外。它支持ListList数组!

如果您需要序列化Dictionary或执行其他操作而不是简单地序列化和反序列化简单数据类型,请使用第三方API。否则,继续阅读。

要序列化的示例类:

1
2
3
4
5
6
7
[Serializable]
public class Player
{
    public string playerId;
    public string playerLoc;
    public string playerNick;
}

1。一个数据对象(非数组JSON)

序列化A部分:

使用public static string ToJson(object obj);方法序列化为Json。

1
2
3
4
5
6
7
8
Player playerInstance = new Player();
playerInstance.playerId ="8484239823";
playerInstance.playerLoc ="Powai";
playerInstance.playerNick ="Random Nick";

//Convert to JSON
string playerToJson = JsonUtility.ToJson(playerInstance);
Debug.Log(playerToJson);

输出:

1
{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"}

序列化B部分:

使用public static string ToJson(object obj, bool prettyPrint);方法重载序列化为Json。只需将true传递给JsonUtility.ToJson函数即可格式化数据。将下面的输出与上面的输出进行比较。

1
2
3
4
5
6
7
8
Player playerInstance = new Player();
playerInstance.playerId ="8484239823";
playerInstance.playerLoc ="Powai";
playerInstance.playerNick ="Random Nick";

//Convert to JSON
string playerToJson = JsonUtility.ToJson(playerInstance, true);
Debug.Log(playerToJson);

输出:

1
2
3
4
5
{
   "playerId":"8484239823",
   "playerLoc":"Powai",
   "playerNick":"Random Nick"
}

反序列化A部分:

使用public static T FromJson(string json);方法重载反序列化json。

1
2
3
string jsonString ="{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"}";
Player player = JsonUtility.FromJson<Player>(jsonString);
Debug.Log(player.playerLoc);

反序列化B部分:

使用public static object FromJson(string json, Type type);方法重载反序列化json。

1
2
3
string jsonString ="{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"}";
Player player = (Player)JsonUtility.FromJson(jsonString, typeof(Player));
Debug.Log(player.playerLoc);

反序列化C部分:

使用public static void FromJsonOverwrite(string json, object objectToOverwrite);方法反序列化json。使用JsonUtility.FromJsonOverwrite时,将不会创建要反序列化的该Object的新实例。它只会重复使用您传入的实例并覆盖其值。

这是有效的,应尽可能使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Player playerInstance;
void Start()
{
    //Must create instance once
    playerInstance = new Player();
    deserialize();
}

void deserialize()
{
    string jsonString ="{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"}";

    //Overwrite the values in the existing class instance"playerInstance". Less memory Allocation
    JsonUtility.FromJsonOverwrite(jsonString, playerInstance);
    Debug.Log(playerInstance.playerLoc);
}

2。多重数据(ARRAY JSON)

您的Json包含多个数据对象。例如,playerId出现了不止一次。 Unity的JsonUtility不支持数组,因为它仍然是新的,但是您可以使用此人的帮助器类来使数组与JsonUtility一起使用。

创建一个名为JsonHelper的类。从下面直接复制JsonHelper。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public static class JsonHelper
{
    public static T[] FromJson< T >(string json)
    {
        Wrapper< T > wrapper = JsonUtility.FromJson<Wrapper< T >>(json);
        return wrapper.Items;
    }

    public static string ToJson< T >(T[] array)
    {
        Wrapper< T > wrapper = new Wrapper< T >();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper);
    }

    public static string ToJson< T >(T[] array, bool prettyPrint)
    {
        Wrapper< T > wrapper = new Wrapper< T >();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper, prettyPrint);
    }

    [Serializable]
    private class Wrapper< T >
    {
        public T[] Items;
    }
}

序列化Json数组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Player[] playerInstance = new Player[2];

playerInstance[0] = new Player();
playerInstance[0].playerId ="8484239823";
playerInstance[0].playerLoc ="Powai";
playerInstance[0].playerNick ="Random Nick";

playerInstance[1] = new Player();
playerInstance[1].playerId ="512343283";
playerInstance[1].playerLoc ="User2";
playerInstance[1].playerNick ="Rand Nick 2";

//Convert to JSON
string playerToJson = JsonHelper.ToJson(playerInstance, true);
Debug.Log(playerToJson);

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
   "Items": [
        {
           "playerId":"8484239823",
           "playerLoc":"Powai",
           "playerNick":"Random Nick"
        },
        {
           "playerId":"512343283",
           "playerLoc":"User2",
           "playerNick":"Rand Nick 2"
        }
    ]
}

反序列化Json数组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
string jsonString ="{\
\
    "
Items": [\
\
        {\
\
            "
playerId": "8484239823",\
\
            "
playerLoc": "Powai",\
\
            "
playerNick": "Random Nick"\
\
        },\
\
        {\
\
            "
playerId": "512343283",\
\
            "
playerLoc": "User2",\
\
            "
playerNick": "Rand Nick 2"\
\
        }\
\
    ]\
\
}"
;

Player[] player = JsonHelper.FromJson<Player>(jsonString);
Debug.Log(player[0].playerLoc);
Debug.Log(player[1].playerLoc);

输出:

Powai

User2

如果这是来自服务器的Json数组,而您没有手动创建它:

您可能必须在接收到的字符串之前添加{"Items":,然后在其末尾添加}

我为此做了一个简单的功能:

1
2
3
4
5
string fixJson(string value)
{
    value ="{"Items":" + value +"}";
    return value;
}

然后您可以使用它:

1
2
string jsonString = fixJson(yourJsonFromServer);
Player[] player = JsonHelper.FromJson<Player>(jsonString);

3。不带类反序列化json字符串


n


n


n


n


n


n


就像@Maximiliangerhardt所说,MiniJson没有正确反序列化的能力。我使用了JsonFx并像魅力一样工作。与[]

一起使用

1
2
player[] p = JsonReader.Deserialize<player[]>(serviceData);
Debug.Log(p[0].playerId +""+ p[0].playerLoc+"--"+ p[1].playerId +"" + p[1].playerLoc+"--"+ p[2].playerId +"" + p[2].playerLoc);

不要修整[],您应该会好起来的。 []标识一个JSON数组,正是您需要对其进行迭代的元素。