最近遇到了一个解析json字符串的问题。由于嵌套的节点较多,刚开始通过遍历的方式去获取,但是遍历首先就是逻辑麻烦,然后想要你需要的东西可能会比较困难。后面发现json的节点是不变的,那么可以通过JsonConvert将json字符串转成指定的model,而这个model所含有的字段要和字符串中的节点一样,如果节点下还有嵌套的,那么再将此节点写成一个model,依次类推。
有这样一个字符串:
{ "message": { "event_type": "transcodeComplete", "transcode_info": { "title": "title", "status": "SUCCEED", "template_group_name": "mp4_adptive_template_group", "output": [ { "play_type": "MP4", "url": "https://www.baidu.com", "encrypted": 0, "meta_data": { "play_type": 0, "codec": "H.264", "duration": 57, "video_size": 18359296, "width": 1280, "hight": 720, "bit_rate": 2499, "frame_rate": 0, "audio_channels": 0 } } ], "asset_id": "3ada15adc1df40ce0b2a7f98c35ca2de" } } }
我们可以将其写成几个model,一个大的model,msg,包含所有信息,就叫message吧。其下还有transcode_info,transcode_info下还有output,记住,output是一个数组,需要用list来存储,output下还有meta_data。就这样。记住:名称必须和节点名称一致!名称必须和节点名称一致!名称必须和节点名称一致!
下面开始:
Message:
public class Message { /// <summary> /// /// </summary> public string event_type { get; set; } /// <summary> /// /// </summary> public Transcode_info transcode_info { get; set; } }
Transcode_info
public class Transcode_info { /// <summary> /// /// </summary> public string title { get; set; } /// <summary> /// /// </summary> public string asset_id { get; set; } /// <summary> /// /// </summary> public string status { get; set; } /// <summary> /// /// </summary> public string templateGroupName { get; set; } /// <summary> /// /// </summary> public List<OutputItem> output { get; set; } /// <summary> /// /// </summary> public string error_code { get; set; } /// <summary> /// /// </summary> public string error_msg { get; set; } }
Output
public class OutputItem { /// <summary> /// /// </summary> public string play_type { get; set; } /// <summary> /// /// </summary> public string url { get; set; } /// <summary> /// /// </summary> public int encrypted { get; set; } /// <summary> /// /// </summary> public string quality { get; set; } /// <summary> /// /// </summary> public meta_data meta_data { get; set; } }
meta_data:
public class meta_data { /// <summary> /// /// </summary> public int play_type { get; set; } /// <summary> /// /// </summary> public string codec { get; set; } /// <summary> /// /// </summary> public int duration { get; set; } /// <summary> /// /// </summary> public int video_size { get; set; } /// <summary> /// /// </summary> public int width { get; set; } /// <summary> /// /// </summary> public int hight { get; set; } /// <summary> /// /// </summary> public int bit_rate { get; set; } /// <summary> /// /// </summary> public int frame_rate { get; set; } /// <summary> /// /// </summary> public int quality { get; set; } /// <summary> /// /// </summary> public int audio_channels { get; set; } }
以上,就是对所有节点建立的model。
然后进行转换的时候,只需要
Message msg = JsonConvert.DeserializeObject<Message>("你的json字符串");就可以了。
以上是学习的心得,大家有更好的方法可以告知在下,谢谢!