在unity3d中,当从服务器加载数据是json字符串时,我们就需要解析并存储它,(在这里我将接收的数据打印输出)
下方数据是我接收到的字符串:
{"success": true,"message": "","data": {"id": "mmd","texture_url": "贴图下载路径,请补充","model_url": "模型下载路径,请补充","industry": [{"title": "室外","icon": "ClsIcon_Building.png","children": [{"title": "圈地","children": [{"id": "5a250ed1b93b455e81b8c659fe528a89","title": "圈地(无框)","type": "WallPrefab","version": "2","size": [1.0,0.01,0.06]},{"id": "9DD39737B6D14BD4B369D124F052C0CB","title": "马路牙","type": "WallPrefab","version": "7","size": [1.0,0.2,0.2]},{"id": "0ae01d1114d04a889816b4af9b951a93","title": "绿化带","type": "WallPrefab","version": "1","size": [1.2,0.645848,0.65]}]}]}]}}
看到这个字符串的时候,我们能够知道这是个json字符串,但结构的话不太好看出来,所以我们需要借助一个工具来格式化一下:如图:
网址如下:json在线解析
打开之后将上面得到的字符串复制下来,操作如下图:粘贴到这里后点击格式化校验就能看到如图效果
这样就很容易看出这个json字符串的结构了。(在json中大括号可以定义类,中括号可以定义数组,字段的名字要一一对应)
下面的代码就是我根据这个字符串的结构定义的一些类:
[System.Serializable]
public class A
{
public string success;
public string message;
public B data;
}
[System.Serializable]
public class B
{
public string id;
public string texture_url;
public string model_url;
public C[] industry;
}
[System.Serializable]
public class C
{
public string title;
public string icon;
public D[] children;
}
[System.Serializable]
public class D
{
public string title;
public E[] children;
}
[System.Serializable]
public class E
{
public string id;
public string title;
public string type;
public string version;
public string[] size;
}
这些全部做好后,才可以接收并输出里面的数据。
1:我们就用unity3d中的JsonUtility来接收,代码如下:
//s:接收到的字符串
A a = JsonUtility.FromJson<A>(s);
print(a.success);
print(a.message);
print("data.id::"+a.data.id);
print("data.texture_url::" + a.data.texture_url);
print(a.data.industry[0].title);
print(a.data.industry[0].children[0].title);
print(a.data.industry[0].children[0].children[0].id);
打印结果如下:
使用litjson.dll直接接收data信息:这样能直接获取data字符串并读取里面的信息:
JsonData jd = JsonMapper.ToObject(s);
string str1 = JsonMapper.ToJson(jd["data"]);
B b = JsonUtility.FromJson<B>(str1);
print(b.id);
记住这些,再碰到json字符串就不会那么慌了。