我有一个JSON字符串。我想将字符串转换为对象,而无需在之前声明类。如果有对象,此代码将起作用。但是问题是我不能像字典一样使用结果。
JSON字符串示例:
{“代码”:200,“详细信息”:“您的请求已接受”,“数据”:[{“ id”:1,“名称”:“ A”},{“ id”:2,” name“:” Bee“}]}
代码:
void callback(string response)
{
var obj = response as object; // It's not error but this may can't cast to object
var level_1 = obj as Dictionary<string,object>;
print(level_1["code"]); // This should print 200 at Console.
// but it doesn't this shows error "Value cannot be null."
// so the obj variable should be cast to empty object.
"
}
我试图找到,但是我发现仅将字符串转换为声明的类,例如:
[Serializable]
public MyClass()
{
public code;
}
var obj = JsonUtility.FromJson<MyClass>(Json);
有没有一种方法可以将任意JSON字符串转换为对象,而无需声明具有其所有字段的类?
答案 0 :(得分:0)
谢谢你们的有用想法。现在有了您的所有想法,我可以弄清楚。
using Newtonsoft;
void callback(string response)
{
dynamic level_1 = Newtonsoft.Json.JsonConvert.DeserializeObject(response);
print("code: " + level_1.code); // The console now shows 200
}