How to access Json data without unknown key?

前端 未结 2 459
情话喂你
情话喂你 2021-01-29 10:42
public static string RESTToJsonConverter(string incoming_data){
    string data = "[";
    int i = 0;
    Debug.Log("incoming_data"+incoming_data);
          


        
2条回答
  •  迷失自我
    2021-01-29 10:59

    For your specific case I would go the other way round:

    The root field name usually doesn't matter so if you remove the trailing } and start the string from the second { you would have

    {
        "assetName": "avatar",
        "id": "-M4qRmfnFya7bC43Ujye",
        "imageName": "icon_avatar",
        "name": "Bob",
        "objName": "Bobby",
        "point": "-M4vZRY9vhKs65n5L_Gk",
        "versionNumber": "3"
    }
    

    which you can simply create a c# class for

    [Serializable]
    public class Data
    {
        public string assetName;
        public string id;
        public string imageName;
        public string name;
        public string objName;
        public string point;
        public string versionNumber;
    }
    

    and then you could use JsonUtility

    public static Data RESTToJsonConverter(string incoming_data)
    {
        Debug.Log($"incoming_data:/n{incoming_data}");
    
        // remove everything before the SECOND occurrence of '{'
        // remove last occurrence of '}'
        var startIndex = incoming_data.IndexOf('{', incoming_data.IndexOf('{') + 1);
        var endIndex = incoming_data.LastIndexOf('}') - 1;
        var json = incoming_data.Substring(startIndex, endIndex - startIndex);
    
        // then remove leading or trailing whitespace
        json = json.Trim();
        
        Debug.Log($"json:/n{json}");
       
        var data = JsonUtility.FromJson(json);
    
        return data;
    }
    

    Update

    You now updated your question content so now the data comes as a Dictionary of data objects.

    In this case you could use Newtonsoft Json.NET which directly supports (de)serialization of Dictionary like e.g.

    [Serializable]
    public class Data
    {
        public string assetName;
        public string id;
        public string imageName;
        public string name;
        public string objName;
        public string point;
        public string versionNumber;
    }
    

    and then do something like

    public static Dictionary RESTToJsonConverter(string incoming_data)
    {
        Debug.Log($"incoming_data:/n{incoming_data}");
       
        var data = JsonConvert.DeserializeObject(json);
    
        return data;
    }
    

    then you can do e.g.

    var datas = RESTToJsonConverter(receivedRawData);
    foreach(var data in data.Values)
    {
        Debug.Log(data.id);
    }
    

提交回复
热议问题