Json篇-Json详解

1、什么是Json

JSON是一种轻量级的数据交换格式。

2、Json优点

易于人阅读和编写,同时易于机器解析和生成。

3、Json的两种结构

1、对象
用大括号(“{}”)括起来,大括号里是一系列的“名称/值”。

{
    
    
  "id": 1,
  "name": "cidy"
}

2、数组
数组在js中是中括号“[]”扩起来的内容,

{
    
    
  "test":  [
      {
    
    
        "id": 1,
        "name": "cidy"
      },
      {
    
    
        "id": 2,
        "name": "bob"
      },
      {
    
    
        "id": 3,
        "name": "kang"
      }
    ]
}

4、Json的语法规则

数组(Array)用方括号(“[]”)表示。
对象(Object)用大括号(”{}”)表示。
名称/值对(name/value)组合成数组和对象。
名称(name)置于双引号中,值(value)有字符串、数值、布尔值、null、对象和数组。
并列的数据之间用逗号(“,”)分隔,最后一个“名称/值”之后不要加逗号。

5、使用LitJson解析Json

1、解析对象结构的json

public class Info
{
    
    
    public int id;
    public string name;
}
public class JsonTest : MonoBehaviour
{
    
    
    private void Awake()
    {
    
    	//这里把json文件放到StreamingAssets里
        StreamReader reader = File.OpenText(Application.streamingAssetsPath + "/jstext2.json"); //用于从文件中读取数据
        string input = reader.ReadToEnd();
        JsonReader jsonReader = new JsonReader(input);
        Info root = JsonMapper.ToObject<Info>(jsonReader);
        Debug.Log(root.name);
    }

}

2、解析数组结构的json

public class Info
{
    
    
    public int id;
    public string name;
}
public class jsonT
{
    
    
    public List<Info> test= new List<Info>();
}
public class JsonTest : MonoBehaviour
{
    
    
    private void Awake()
    {
    
    
        StreamReader reader = File.OpenText(Application.streamingAssetsPath + "/jstext.json"); //用于从文件中读取数据
        string input = reader.ReadToEnd();
        JsonReader jsonReader = new JsonReader(input);
        jsonT root = JsonMapper.ToObject<jsonT>(jsonReader);
        Debug.Log(root.test[0].name);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_30868065/article/details/121432837