代码之家  ›  专栏  ›  技术社区  ›  Siddharth

通过Dictionary对象解析Json响应

  •  0
  • Siddharth  · 技术社区  · 6 年前

    我通过Facebook API得到了如下Json响应:

    enter image description here

    现在我想分析这些数据以便在游戏中使用。为此,我编写了以下代码:

     public void OnChallengesButtonClick ()
     {
         SoundManager.Instance.PlayButtonClickSound ();
    
         FB.API ("/me/friends", HttpMethod.GET, RetrieveFacebookFriends);
     }
    
     public void RetrieveFacebookFriends (IGraphResult result)
     {
         if (!string.IsNullOrEmpty (result.Error)) {
             Debug.Log ("ERROR: " + result.Error);
             return;
         }
    
         IDictionary<string,object> friendsDict = result.ResultDictionary;
    
         Debug.Log ("raw: " + result.RawResult);
     }
    

    那么如何提取 名称 身份证件 通过Dictionary对象从可用Json响应得到的数据?

    2 回复  |  直到 6 年前
        1
  •  0
  •   Piotr Krankiewicz    6 年前

    基本上,您应该创建一个类来序列化/反序列化对象:

    class FBResponse
      FBDataResponse data;
    
    class FBDataResponse
      string name;
      string id;
    

    请看我在这里的回答,了解更多细节(在“最终编辑”部分之后): Converting arrays of arrays to json

    创建这两个类并使用它们反序列化FB响应应该很容易。请记住,您的变量需要与来自Facebook的json响应匹配(例如,您不能调用data data1)。

    当你拥有了这个东西之后,你应该可以很容易地用它做你想做的事。。。使用这个对象,您应该能够再次获得json。

    Unity默认的json序列化程序不支持字典,所以需要序列化两个对象。如果你不想,你应该试着用另一个库。

        2
  •  0
  •   Siddharth    6 年前

    我想这就是我所需要的: JSON with Unity

    friends = (List<object>)(((Dictionary<string, object>)friendsH) ["data"]);
    if(friends.Count > 0) {
        var friendDict = ((Dictionary<string,object>)(friends[0]));
        var friend = new Dictionary<string, string>();
        friend["id"] = (string)friendDict["id"];
        friend["first_name"] = (string)friendDict["first_name"];
    }
    

    在我无法从Facebook上找到这篇文章之前。