Json解析(一)
文章目錄
- Json解析(一)
- 介紹
- 一、json檔案展示
- 二、使用步驟
-
- 1.轉換String為Json
- 2.提取文字
- 3.成品代碼展示
- 4.效果
- 總結
介紹
雖然我們的文檔是json解析(一)但是也完全可以使用做json解析
提示:以下是本篇文章正文内容,下面案例可供參考
一、json檔案展示
今天我們需要解析的檔案内容為:
{
"status": "ok",
"results": [{
"text": "\u96be\u53d7",
"score": 0.9967435002326965,
"position": [
[267.0, 267.0],
[412.0, 412.0],
[412.0, 412.0],
[267.0, 267.0]
]
}, {
"text": "\u5ce8",
"score": 0.7575550675392151,
"position": [
[62.0, 62.0],
[142.0, 142.0],
[142.0, 142.0],
[62.0, 62.0]
]
}, {
"text": "\u6211\u8fd8\u80fd\u8bf4\u4ec0\u516c",
"score": 0.420401394367218,
"position": [
[475.0, 475.0],
[662.0, 662.0],
[662.0, 662.0],
[475.0, 475.0]
]
}, {
"text": "\u6ca1\u5fc5\u8981",
"score": 0.9887173175811768,
"position": [
[52.0, 52.0],
[160.0, 160.0],
[160.0, 160.0],
[52.0, 52.0]
]
}, {
"text": "\u884c\u884c\u884c\u4f60\u8bf4\u4e86\u7b97",
"score": 0.9628203511238098,
"position": [
[269.0, 269.0],
[677.0, 677.0],
[677.0, 677.0],
[269.0, 269.0]
]
}, {
"text": "\u5fc3\u5982\u6b7b\u7070",
"score": 0.9149372577667236,
"position": [
[99.0, 99.0],
[557.0, 557.0],
[556.0, 556.0],
[98.0, 98.0]
]
}, {
"text": "690\u00d7624",
"score": 0.8837266564369202,
"position": [
[616.0, 616.0],
[683.0, 683.0],
[683.0, 683.0],
[616.0, 616.0]
]
}]
}
二、使用步驟
1.轉換String為Json
其中我們的data是我們需要轉換的字元串
responseJson則是給我們的檔案序列化
string responseString = data;
JObject responseJson = JObject.Parse(responseString);
2.提取文字
擷取“status”字段的值
擷取“results”字段的值
JArray resultsArray = (JArray)responseJson["results"];
List<JToken> results = resultsArray.ToList();
“results”清單中擷取每個結果對象的值
JArray positionArray = (JArray)item["position"];
List<Vector2> positionList = new List<Vector2>();
foreach (JArray point in positionArray)
{
float x = (float)point[0];
float y = (float)point[1];
positionList.Add(new Vector2(x, y));
}
3.成品代碼展示
代碼如下(示例):
void JsonText()
{
string responseString = data;
JObject responseJson = JObject.Parse(responseString);
//要擷取“status”字段的值
string status = (string)responseJson["status"];
//要擷取“results”字段的值
JArray resultsArray = (JArray)responseJson["results"];
List<JToken> results = resultsArray.ToList();
//“results”清單中擷取每個結果對象的值
foreach (var item in results)
{
Debug.Log("text: " + item["text"]);
Debug.Log("score: " + item["score"]);
//texts.text += "text: " + item["text"]+"\n";
//texts.text += "score: " + item["score"]+"\n";
JArray positionArray = (JArray)item["position"];
List<Vector2> positionList = new List<Vector2>();
foreach (JArray point in positionArray)
{
float x = (float)point[0];
float y = (float)point[1];
positionList.Add(new Vector2(x, y));
Debug.Log("x: " + x + " " + "y: " + y);
//texts.text += "x: " + x+"\n";
//texts.text += "y: " + y+"\n";
}
}
4.效果
代碼如下(示例):
總結
提示:這裡對文章進行總結:
文章技能靈活使用,本文方法非常簡單