Json解析
Posted 露夕逝
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Json解析相关的知识,希望对你有一定的参考价值。
#region Json解析相关 /// <summary> /// 从json中读取数据 /// </summary> /// <param name="json"></param> /// <returns></returns> List<SceneData> GetSceneDataListFromJson(string json) { List<SceneData> sceneDataList = new List<SceneData>(); List<string> sceneNameList = GetValueListFromJson(json, "sceneName"); List<string> snList = GetValueListFromJson(json, "sn"); List<string> timeList = GetValueListFromJson(json, "time"); List<string> posDataList = GetValueListFromJson(json, "posList"); if (sceneNameList.Count * 4 != (sceneNameList.Count + snList.Count + timeList.Count + posDataList.Count)) { Debug.LogError("json解析各属性数目不符!"); return null; } for (int i = 0; i < sceneNameList.Count; i++) { SceneData sceneData = new SceneData(); sceneData.sceneName = sceneNameList[i]; sceneData.sn = int.Parse(snList[i]); sceneData.time = int.Parse(timeList[i]); string posListStr = posDataList[i]; List<Vector2> posList = new List<Vector2>(); string[] coordArr = posListStr.Split(‘,‘); for (int m = 0; m < coordArr.Length; m++) { string[] coord = coordArr[m].Split(‘_‘); float x = float.Parse(coord[0]); float y = float.Parse(coord[1]); posList.Add(new Vector2(x, y)); } sceneData.posList = posList; sceneDataList.Add(sceneData); } return sceneDataList; } List<string> GetValueListFromJson(string json, string valueName) { List<string> valueList = new List<string>(); while (true) { int endIndex = json.Length - 1; string valueStr = GetFirstValueFromJson(json, valueName, out endIndex); if (valueStr == null) { break; } valueList.Add(valueStr); json = json.Substring(endIndex); } if (valueList.Count == 0) { Debug.LogError("can‘t find the " + valueName + " from json!"); } return valueList; } string GetFirstValueFromJson(string json, string valueName, out int endIndex) { int beginIndex = json.IndexOf(valueName); if (beginIndex == -1) { endIndex = json.Length - 1; return null; } endIndex = json.IndexOf(‘,‘, beginIndex); int preLength = valueName.Length + 2; string goalStr = json.Substring(beginIndex, endIndex - beginIndex); if (goalStr.Contains("["))//如果包含数组 { endIndex = json.IndexOf("]") + 1; goalStr = json.Substring(beginIndex, endIndex - beginIndex); } goalStr = goalStr.Substring(preLength, goalStr.Length - preLength); goalStr = goalStr.Replace(""", ""); goalStr = goalStr.Replace("[", ""); goalStr = goalStr.Replace("]", ""); return goalStr; } #endregion