MINIJson Unity获得嵌套的json对象

时间:2016-06-13 06:29:30

标签: c# json unity3d

{ “检查”:“成功”, “统计”:{ “2”:{ “等级”:1, “分数”: “2000”, “名”:“穆罕默德” }, “3”:{ “等级”:1, “分数”: “2000”, “名”:“拉姆齐” }}}

这是我的json字符串。我想使用“stats”作为列表来检查它有多少条目。然后我需要从每个条目中获得等级,名称,分数等。 我的代码是,

var result = Json.Deserialize(jsontest) as Dictionary<string,object>;
    object st;
    var rankholders = new List<object>();
    if (result.TryGetValue("stats", out st))
    {
        rankholders = (List<object>)(((Dictionary<string, object>)st)["stats"]);
        foreach (object obj in rankholders)
        {
            var tempDict = ((Dictionary<string,object>)(rankholders[0]));
            WeeklyStatsItem tempRow = new WeeklyStatsItem ();
            tempRow.rank = (string)tempDict["rank"];
            tempRow.name = (string)tempDict["name"];
            tempRow.score = (string)tempDict["score"];
            weeklyScoreList.Add (tempRow);
        }
    }

但是我得到了keynotfound异常。知道如何解析这样的json循环吗?

3 个答案:

答案 0 :(得分:0)

对我来说,看起来你有一个包含财产的对象&#34;检查&#34;和一个名为&#34; stats&#34;的字典。如果您将使用此结构创建自己的类,则可以将json反序列化为此类对象 类似的东西:

class Stats
{
public int rank;
public int score;
public string name;
}

class ResultContainer
{
public string checked;
public Dictionary<int,Stats>stats;
}

你应该反序列化为ResultContainer。

答案 1 :(得分:-1)

您的Json无效,因为当stats成为List或数组时,它会抛出错误。我能够使用以下代码重新创建一个有效的Json:

  

我想使用“stats”作为列表来检查它有多少条目

WeeklyStatsItem recreation = new WeeklyStatsItem();
recreation.check = "success";

recreation.stats = new List<Stats>();

Stats st1 = new Stats();
st1.rank = 1;
st1.score = "2000";
st1.name = "Muhammad";
recreation.stats.Add(st1);

Stats st2 = new Stats();
st2.rank = 1;
st2.score = "2000";
st2.name = "Ramsay";
recreation.stats.Add(st2);

Debug.Log(JsonUtility.ToJson(recreation));

新生成的有效Json是:

{"check":"success","stats":[{"rank":1,"score":"2000","name":"Muhammad"},{"rank":1,"score":"2000","name":"Ramsay"}]}

现在回答你的问题:

  

我想使用“stats”作为列表来检查它有多少条目。

string jsonTest = "{\"check\":\"success\",\"stats\":[{\"rank\":1,\"score\":\"2000\",\"name\":\"Muhammad\"},{\"rank\":1,\"score\":\"2000\",\"name\":\"Ramsay\"}]}";
WeeklyStatsItem weeklyIt = JsonUtility.FromJson<WeeklyStatsItem>(jsonTest);
Debug.Log(weeklyIt.stats.Count);
  

然后我需要从每个条目中获得等级,名称,分数等

string jsonTest = "{\"check\":\"success\",\"stats\":[{\"rank\":1,\"score\":\"2000\",\"name\":\"Muhammad\"},{\"rank\":1,\"score\":\"2000\",\"name\":\"Ramsay\"}]}";
WeeklyStatsItem weeklyIt = JsonUtility.FromJson<WeeklyStatsItem>(jsonTest);

Debug.Log("CHECK: " + weeklyIt.check);
for (int i = 0; i < weeklyIt.stats.Count; i++)
{
    Debug.Log("STATS INDEX: " + i);
    Debug.Log("RANK: " + weeklyIt.stats[i].rank);
    Debug.Log("NAME: " + weeklyIt.stats[i].name);
    Debug.Log("SCORE: " + weeklyIt.stats[i].score);
}

你的Json课程:

[Serializable]
public class Stats
{
    public int rank;
    public string score;
    public string name;
}

[Serializable]
public class WeeklyStatsItem
{
    public string check;
    public List<Stats> stats;
}

答案 2 :(得分:-1)

由于您的密钥具有语义含义且不会映射到变量名称,因此您必须比假设您的json对象整齐地映射到ac#对象的基本示例更进一步,即他们有一个固定的架构。

基本上,您必须查看stats dict中的每个条目,并将密钥和基础值都传递给域对象构造函数。

我对MiniJSON并不是很熟悉,但我已经把一个有效的例子拼凑在了一起。我怀疑有一种更惯用的做法,例如:使用泛型。

资产/编辑/ ParserTest.cs


using NUnit.Framework;

public class ParserTest {

    [Test]
    public void TestThatTwoPlayersAreInTestResponse()
    {
        string testResponse = "{ \"check\":\"success\", \"stats\":{ \"2\":{ \"rank\":1, \"score\":\"2000\", \"name\":\"Muhammad\" }, \"3\":{ \"rank\":1, \"score\":\"2000\", \"name\":\"Ramsay\" } } }";
        Assert.AreEqual(MiniJsonParsingExample.parseResponse(testResponse).Count, 2);
    }
}

资产/脚本/ MiniJsonParsingExample.cs


using System.Collections.Generic;
using Facebook.MiniJSON;

public class MiniJsonParsingExample
{

    public static List parseResponse(string responseText)
    {
        var resultDict = Json.Deserialize(responseText) as Dictionary;
        var players = new List();
        if (resultDict.ContainsKey("stats"))
        {
            var playerDict = resultDict["stats"] as Dictionary;
            foreach (string playerId in playerDict.Keys)
            {
                var psuedoPlayer = playerDict[playerId] as Dictionary;
                string playerName = psuedoPlayer["name"] as string;
                long playerRank = (long) psuedoPlayer["rank"];
                string playerScore = psuedoPlayer["score"] as string;
                players.Add(new Player(playerId, playerName, playerRank, playerScore));
            }
        }
        return players;
    }

    public class Player
    {
        string id;
        string name;
        long rank;
        string score;

        public Player(string id, string name, long rank, string score)
        {
            this.id = id;
            this.name = name;
            this.rank = rank;
            this.score = score;
        }
    }
}