问题
同一个接口返回不同类型的json,json结构相差比较大转换为C#对象不太合适,想着是否可以动态解析。
newtonsoft类
JTokenType类型
namespace Newtonsoft.Json.Linq
{/// <summary>/// Specifies the type of token./// </summary>public enum JTokenType{/// <summary>/// 未知类型/// </summary>None = 0,/// <summary>/// JSON对象/// </summary>Object = 1,/// <summary>/// JSON数组/// </summary>Array = 2,/// <summary>/// JSON 构造函数/// </summary>Constructor = 3,/// <summary>/// JSON对象的属性/// </summary>Property = 4,/// <summary>/// 备注/// </summary>Comment = 5,/// <summary>/// 整数值/// </summary>Integer = 6,/// <summary>/// 浮点数/// </summary>Float = 7,/// <summary>/// 字符串/// </summary>String = 8,/// <summary>/// 布尔值/// </summary>Boolean = 9,/// <summary>/// null值/// </summary>Null = 10,/// <summary>/// undefined值/// </summary>Undefined = 11,/// <summary>/// 时间类型/// </summary>Date = 12,/// <summary>/// 原始的json值/// </summary>Raw = 13,/// <summary>/// 字节值的集合/// </summary>Bytes = 14,/// <summary>/// GUID值/// </summary>Guid = 15,/// <summary>/// Uri值/// </summary>Uri = 16,/// <summary>/// 时间戳值/// </summary>TimeSpan = 17}
}
读取
JToken
// 以下两种写法都可以被转换为 JToken 类型
string jtokenstring1 = "\"Hello World\"";
string jtokenstring2 = "{\"name\":\"John\",\"age\":30}";
string jtokenstring3 = "10";
JToken jtoken1 = JToken.Parse(jtokenstring1);
Console.WriteLine(jtoken1.Type);
Console.WriteLine(jtoken1.HasValues);
JToken jtoken2 = (JToken)JsonConvert.DeserializeObject(jtokenstring2);
Console.WriteLine(jtoken2.Type);
Console.WriteLine(jtoken2.HasValues);
JToken jtoken3 = JToken.Parse(jtokenstring3);
Console.WriteLine(jtoken3.Type);
Console.WriteLine(jtoken3.HasValues);
JObject
// 只能序列化标准的 json 字符串
string jobjstring2 = "{\"name\":\"John\",\"age\":30}";
JObject jobj1 = JObject.Parse(jobjstring2);
JObject jobj2 = (JObject)JsonConvert.DeserializeObject(jobjstring2);
Console.WriteLine(jobj1.Type);
Console.WriteLine(jobj1.HasValues);
Console.WriteLine(jobj2.Type);
Console.WriteLine(jobj2.HasValues);
JArray
// 以下两种写法都可解析
// 主要标识就是字符串两段是中括号
string jarraystring1 = "[\"value1\",\"value2\"]";
string jarraystring2 = "[{\"name\":\"John\",\"age\":30},{\"name\":\"Bob\",\"age\":20}]";
JArray jarray1 = JArray.Parse(jarraystring2);
JArray jarray2 = (JArray)JsonConvert.DeserializeObject(jarraystring2);
Console.WriteLine(jarray1.Type);
Console.WriteLine(jarray1.HasValues);
Console.WriteLine(jarray2.Type);
Console.WriteLine(jarray2.HasValues);
JProperty
//在JObject中是一个name/JToken键值对
string jobjstring2 = "{\"name\":\"John\",\"age\":30}";
JObject jobj1 = JObject.Parse(jobjstring2);
if (jobj1.HasValues)
{foreach (var property in jobj1.Values<JProperty>()){Console.WriteLine(property.Name);Console.WriteLine(property.Type);Console.WriteLine(property.Value);}
}
JValue
JObject jsonObject = JObject.Parse("{\"a\":10,\"b\":\"Hello World\",\"c\":10}");
// 获取值信息
JValue jvaluea = (JValue)jsonObject["a"];
JValue jvalueb = (JValue)jsonObject["b"];
JValue jvaluec = (JValue)jsonObject["c"];
// JValue 两个实例比较
Console.WriteLine("jvaluea.Equals(jvalueb): " + jvaluea.Equals(jvalueb)); // false
Console.WriteLine("jvaluea.Equals(jvaluec): " + jvaluea.Equals(jvaluec)); // true
Console.WriteLine("jvaluea==jvaluec: " + (jvaluea == jvaluec)); // false
Console.WriteLine("jvalueb: " + jvalueb); // Hello World
int intValue = jvaluea.Value<int>(); // 将值转换为整数类型
Console.WriteLine("Integer value: " + intValue);
只知道是个json字符串如何解析全部的数据
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;namespace JsonStu01;class Program
{static void Main(string[] args){ExampleData data = new ExampleData { StringValue = "Hello, World!", IntValue = 123, DoubleValue = 456.789, BooleanValue = true, DateTimeValue = DateTime.Now, ArrayValue = new object[] { "item1", 2, 3.14, false, null }, NestedObject = new ExampleNestedData { NestedStringValue = "Nested Value" }, NullableIntValue = 100 // 或者你可以设置为 null 来表示它是可空的 }; string jsonString = JsonConvert.SerializeObject(data, Formatting.Indented);Console.WriteLine(jsonString);var jToken = JToken.Parse(jsonString);Console.WriteLine("========================================");JTokenParsePrint(jToken);Console.WriteLine("========================================");JTokenParsePrint2(jToken);}static void JTokenParsePrint(JToken jToken){if (jToken.HasValues){foreach (var value in jToken.Values()){if (value.HasValues){JTokenParsePrint(value);}else{var res = value as JValue;if (res != null){Console.WriteLine(res);}else{Console.WriteLine("强制转化失败");Console.WriteLine(value.Type);}}}}else{var value = jToken as JValue;Console.WriteLine(value);}}static void JTokenParsePrint2(JToken jToken){if (jToken is JObject jObject) { foreach (JProperty property in jObject.Properties()) { if (property.Value.Type == JTokenType.Object || property.Value.Type == JTokenType.Array) { //Console.WriteLine("--- Nested Value ---"); Console.WriteLine($"Property Name: {property.Name}");JTokenParsePrint2(property.Value); // 递归调用 //Console.WriteLine("--- End Nested Value ---"); }else{Console.WriteLine($"Property Name: {property.Name}, Value: {property.Value}"); }} } else if (jToken is JArray jArray) { foreach (JToken item in jArray) { if (item.Type == JTokenType.Object || item.Type == JTokenType.Array) { //Console.WriteLine("--- Nested Value ---"); JTokenParsePrint2(item); // 递归调用 //Console.WriteLine("--- End Nested Value ---"); }else{Console.WriteLine("Array Item: " + item); }} } else { Console.WriteLine("Token Value: " + jToken); } }
}public class ExampleNestedData
{ public string NestedStringValue { get; set; }
} public class ExampleData
{ public string StringValue { get; set; } public int IntValue { get; set; } public double DoubleValue { get; set; } public bool BooleanValue { get; set; } public DateTime DateTimeValue { get; set; } public object[] ArrayValue { get; set; } public ExampleNestedData NestedObject { get; set; } public Nullable<int> NullableIntValue { get; set; }
}
生成json
JToken
JTokenWriter writer = new JTokenWriter();
writer.WriteStartObject();
writer.WritePropertyName("Title");
writer.WriteValue("aaaaaaa???");writer.WritePropertyName("Detail"); writer.WriteStartArray();
writer.WriteValue("Yes");
writer.WriteValue("No");
writer.WriteValue("Unknown");
writer.WriteEndArray();writer.WriteEndObject();JObject o = (JObject)writer.Token;
Console.WriteLine(o.ToString());
JObject
JObject o = new JObject
{{"CPU","Intel"},{"Memory",2048},{"Drives",new JArray{"DVD","U盘"}}
};Console.WriteLine(o.ToString());
JArray
var array = new JArray();
array.Add(new JObject()
{{ "pkgType","type"},{ "pkgPart","pkgPart"},{ "pkgLotId","pkgLotId"},{ "dateCode","dateCode"},{ "dateTime",System.DateTime.Now.ToString()}
});
//不能添加JProperty
Console.WriteLine(array.ToString());
JProperty
// 创建一个 JProperty 的对象,然后转成字符串值
string propertyname = "name";
string propertyvalue = "John";
JProperty jproperty = new JProperty(propertyname, propertyvalue);
var jp = jproperty.ToString(); // 结果:"name": "John"
Console.WriteLine(jp);
// 下面将 jproperty 对象加入 JObject
JObject jobject = new JObject(); // 将 JProperty 添加到 JObject 中
jobject.Add(jproperty);
string jsonstring = jobject.ToString(); // 将 JObject 转换为字符串
Console.WriteLine(jsonstring);
// 输出:{\r\n \"name\": \"John\"\r\n}
// 但是通过这个输出的格式进行序列化时,就会提示异常,如下:
string jpropertystring1 = "\"name\": \"John\"";
// Newtonsoft.Json.JsonReaderException:Additional text encountered after finished reading JSON content
var jProperty1 = JProperty.Parse(jpropertystring1);
var jProperty2 = (JProperty)JsonConvert.DeserializeObject(jpropertystring1);
JValue
Console.WriteLine(new JValue("aaa").ToString());
Console.WriteLine(new JValue(true).ToString());
Console.WriteLine(new JValue(new Uri("https://hao.360.com/")).ToString());
JObject obj = new JObject();
obj.Add("aaa",new JValue("aaa"));
var arr = new JArray();
arr.Add(new JValue(100));
arr.Add(new JValue(10.0));
arr.Add(new JValue(true));
obj.Add("array",arr);
Console.WriteLine(obj.ToString());
JSON合并
//JSON合并
var o1Str = @"{'FirstName': 'John','LastName': 'Smith','Enabled': false,'Roles': [ 'User' ]}";
var o2Str = @"{'Enabled': true,'Roles': [ 'Admin' ]}";
JObject o1 = JObject.Parse(o1Str);
JObject o2 = JObject.Parse(o2Str);o1.Merge(o2, new JsonMergeSettings
{// union arrays together to avoid duplicatesMergeArrayHandling = MergeArrayHandling.Union
});Console.WriteLine(o1.ToString());
参考
https://www.cnblogs.com/fanfan-90/p/12659937.html
https://www.cnblogs.com/hnzhengfy/p/JObjectJArray.html