定义多个结构体,将结构体内容输入到最终的JObject中,然后将其转为字符串打印出来,即可。
代码内容如下:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;public class Test : MonoBehaviour
{private Apple apple;private Banana banana;private void Start(){apple = new Apple();apple.color = "red";apple.size = 10;apple.breed = "红富士";Monkey monkey = new Monkey();monkey.breed = "金丝猴";monkey.habitat = "高山密林";banana = new Banana();banana.breed = "芭蕉";banana.monkey = (JObject)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(monkey));JObject fruitJObject = new JObject();fruitJObject["Apple"] = (JObject)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(apple));fruitJObject["Banana"] = (JObject)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(banana));Debug.Log(fruitJObject.ToString());}
}/// <summary>
/// 苹果结构体
/// </summary>
struct Apple
{public string color;public int size;public string breed;
}/// <summary>
/// 香蕉结构体
/// </summary>
struct Banana
{public string breed;//!<品种public JObject monkey;//!<猴子
}/// <summary>
/// 猴子结构体
/// </summary>
struct Monkey
{public string breed;//!<品种public string habitat;//!<栖息地
}
运行结果如下:
将接收到的json字符串转为JObject类型,然后取出对应的值并打印出来,代码如下:
string jsonStr = fruitJObject.ToString();JObject jsonJObject = (JObject)JsonConvert.DeserializeObject(jsonStr);Apple appleObject = JsonConvert.DeserializeObject<Apple>(JsonConvert.SerializeObject(jsonJObject["Apple"]));Debug.Log(appleObject.breed);
运行结果如下: