第一次用litjson的时候,在网上搜资料,各种各样的写法,我绕了好大的圈才搞懂。
今天又被人问道LitJson读取json文件,他也没在网上找到很好的解释。json是用得比较多的存储方式,解析json并不难,新手容易搞不清json格式
这次我们解析一个较长的json文件,json数据是在聚合数据下的,额这个也教一下吧,下json数据的教学放在文章的后面,上传成功json文件
一、解析json数据
首先我们先解析一个简单的json数据(文件中一段数据)方便更好的理解
"uniquekey": "db67681bab14888f5987ade34d5f142a", "title": "印度第二季度GDP跌幅创纪录 印媒:政府无力应对,更糟的还在后面", "date": "2020-09-01 15:51", "category": "头条", "author_name": "海外网", "url": "https://mini.eastday.com/mobile/200901155130220.html", "thumbnail_pic_s": "https://01imgmini.eastday.com/mobile//130_a8cf4ae72a8d859e1b2b89846_1_mwpm_0.jpg"
讯享网
不多说直接上代码,记得引用LitJson
讯享网 void Start() {
string data = "{'uniquekey': 'db67681bab14888f5987ade34d5f142a','title': '印度第二季度GDP跌幅创纪录 印媒:政府无力应对,更糟的还在后面','date': '2020-09-01 15:51','category': '头条','author_name': '海外网','url': 'https://mini.eastday.com/mobile/200901155130220.html','thumbnail_pic_s': 'https://01imgmini.eastday.com/mobile/20200901/20200901155130_8455710a8cf4ae72a8d859e1b2b89846_1_mwpm_03200403.jpg'}"; JsonData jsonData = JsonMapper.ToObject(data); Debug.Log("uniquekey==="+jsonData["uniquekey"]); Debug.Log("title===" + jsonData["title"]); Debug.Log("author_name===" + jsonData["author_name"]); }
可以得出结果
二、解析Json文件
把json文件放在StreamingAssets下,先来看下json数据是什么样的(部分截图)

直接上代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using LitJson; using System.IO; public class NewsData {
public string uniquekey; public string title; public string author_name; public string url; public NewsData(string uniquekey,string title,string author_name,string url) {
this.uniquekey = uniquekey; this.title = title; this.author_name = author_name; this.url = url; } } public class TestLitJson : MonoBehaviour {
void Start() {
JieXiJson(); } void JieXiJson() {
List<NewsData> newsList = new List<NewsData>(); string path = Application.streamingAssetsPath + "/TestJson.txt"; //读取文件 StreamReader tmpReader = File.OpenText(path); string result = tmpReader.ReadToEnd(); //Debug.Log(result); JsonData json = JsonMapper.ToObject(result); //转换所需数据 JsonData newsJson = json["result"]["data"]; for (int i = 0; i <newsJson.Count; i++) {
string uniquekey = (string)newsJson[i]["uniquekey"]; string title= (string)newsJson[i]["title"]; string author_name= (string)newsJson[i]["author_name"]; string url= (string)newsJson[i]["url"]; //存入信息 NewsData news = new NewsData(uniquekey, title, author_name, url); newsList.Add(news); } for (int i = 0; i < newsList.Count; i++) {
Debug.Log("第"+(i+1)+"条新闻是 "+newsList[i].title); Debug.Log("第" + (i + 1) + "条uniquekey是 " + newsList[i].uniquekey); Debug.Log("第" + (i + 1) + "条author_name是 " + newsList[i].author_name); Debug.Log("第" + (i + 1) + "条url是 " + newsList[i].url); } } }
运行得到结果

json数据下载
补充下第四步 填key进去之后得到一组数据,复制之后进行转义



版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/62616.html