虽然我们的文档是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]
]
}]
}
其中我们的data是我们需要转换的字符串
responseJson则是给我们的文件序列化
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”列表中获取每个结果对象的值
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));
}
代码如下(示例):
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";
}
}
代码如下(示例):
提示:这里对文章进行总结:
文章技能灵活使用,本文方法非常简单