且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在没有未知密钥的情况下访问Json数据?

更新时间:2022-11-02 23:09:52

对于您的具体情况,我会反其道而行:

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

根字段名称通常无关紧要,因此,如果删除尾随的}并从 second {开始,则需要输入字符串

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"
}

您可以简单地为其创建一个c#类

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;
}

然后可以使用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<Data>(json);

    return data;
}


更新

您现在更新了问题内容,​​因此现在数据作为数据对象的字典出现.


Update

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

在这种情况下,您可以使用 Newtonsoft Json.NET 直接支持对Dictionary例如

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;
}

然后做类似的事情

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

    return data;
}

那么你可以做

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