json格式转换的细节

在开发中经常需要将Json对象转换成目标格式,或者Json字符串反序列成目标对象,此时有一部分需要注意的细节

1.将Json字符串换行输出到“Console”中

在业务逻辑开发中,有时需要将Json字符串换行输出到控制台中,以便仔细查看该字符串内各个属性值,而该Json字符串本身是连续输出的,并没有“换行缩进”那种美观方便的效果。若要查询某个属性的值,只能在控制台日志中仔细查找才行。

因此这里将Json字符串“换行缩进”输出,得到类似“Notepad++”中在安装了“Json Viewer”插件后“Format Json”的效果:

考虑到该对象本身已经是“Json字符串”,如有的项目中服务器发送过来的协议数据(data.msg中的内容)。只是该字符串本身并没有“换行缩进”的美观效果,因此这里将其先反序列化,之后借助“Formatting.Indented”将其再次序列化即可具备“换行缩进”效果

//将返回的json字符串换行输出到控制台中(便于查看)
if (request.responseCode == 200) {
	string msg = request.downloadHandler.text;
	var jsonFormat = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(msg),
		Formatting.Indented);
	Debug.LogFormat("{0}", jsonFormat);
}

该Json字符串原格式如下:

加入“Formatting.Indented”后“换行缩进”效果如下:

2.获取Json字符串中某个具体属性的值

如果该属性在Json字符串中结构较为简单,则可以直接通过匹配该json字符串获取其值

//直接获取json字符串中某个属性的value
if (request.responseCode == 200) {
	string msg = request.downloadHandler.text;
	JObject jsonObject = JObject.Parse(msg);
	string id = jsonObject.GetValue("id").ToString();
	Debug.LogFormat("{0}", id);
}

如上通过“JObject.Parse”直接匹配该Json字符串“msg”,然后获取其内部属性“id”的值即可

效果如下:

3.将Json字符串转换成目标类型的对象

使用Unity中的“JsonUtility.FromJson<T>()”将Json字符串转换成“T”类型的对象。

此时需要注意的是:并非该Json字符串内所有属性值都要在“T”类型中进行一一匹配,只用匹配部分目标属性即可

如将以下Json字符串进行转换:

而实际的转换结构“ChatGPTResponse却并不需要包含Json字符串中的所有属性

“T”类型“ChatGPTResponse”如下:

[System.Serializable]
public class ChatGPTResponse
{
	public string id;
	public ChoiceContent[] choices;
	/*public int created;
	public string model;*/

	[System.Serializable]
	public class ChoiceContent
	{
		public int index;
		public ContentData message;

		//public int logprobs;
		//public string finish_reason;
	}
}



[System.Serializable]
public class ContentData
{
	public string role;
	public string content;
}

/*注意:
*在将json字符串转换成实际的T对象时,并不需要将该json中的所有属性都匹配,
*只需要将需要使用的属性匹配出来即可
*/

实际转换如下:

//将json字符串转换成指定类型对象后再获取其中的具体参数值
ChatGPTResponse response = JsonUtility.FromJson<ChatGPTResponse>(msg);
ChatGPTResponse.ChoiceContent[] contents = response.choices;
if (contents.Length > 0) {
	//去除字符串开头的”\n\n“换行符
	result = contents[0].message.content.TrimStart('\n');
	Debug.LogFormat("{0}", result);
}

输出结果如下:

 PS去除字符串前面的“\n\n”换行符可直接使用“string.TrimStart('\n')”即可

猜你喜欢

转载自blog.csdn.net/m0_47975736/article/details/129660549