我想反序列化JSON为对象,但我不想反序列化嵌套的JSON,嵌套的嵌套JSON应该转换为JSON列表(请检查“ 我的预期输出 ”以获得清晰的主意)…
//假设我下面有JSON数据,在这里我为“地址”实体嵌套了JSON
String jsonEmployees = "{"Employees": [{"EmpId":1, "EmpName":"ABC", "Address":[{"AddressId":1, "Address":"Something"},{"AddressId":2, "Address":"Anything"}]}, {"EmpId":2, "EmpName":"XYZ", "Address":[{"AddressId":1, "Address":"Something"},{"AddressId":2, "Address":"Anything"}]}] }" public class Employee { public int EmpId { get; set; } public string EmpName { get; set; } // **Note** : I'm not using List<Address> data type for Address, instead of I want list of address in JSON string public string Address { get; set; } } public class RootObject { public List<Employee> Employees { get; set; } } var Employees = JsonConvert.DeserializeObject<RootObject>(jsonEmployees);
//我的预期输出
Employees[0].EmpId = 1; Employees[0].EmpName = "ABC"; Employees[0].Address = "[{"AddressId":1, "Address":"Something"},{"AddressId":2, "Address":"Anything"}]"; Employees[1].EmpId = 2; Employees[1].EmpName = "XYZ"; Employees[1].Address = "[{"AddressId":1, "Address":"Something"},{"AddressId":2, "Address":"Anything"}]";
请建议我解决此问题的最佳方法…
您的问题是, 如何 在不转义JSON的情况下 , 如何使用string包含“原始” JSON 的成员对类型进行序列化和反序列化?
string
这可以通过做自定义JsonConverter读取和写入使用原始JSON JsonWriter.WriteRawValue()和JRaw.Create():
JsonConverter
JsonWriter.WriteRawValue()
JRaw.Create()
public class RawConverter : JsonConverter { public override bool CanConvert(Type objectType) { throw new NotImplementedException(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; var raw = JRaw.Create(reader); return raw.ToString(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var s = (string)value; writer.WriteRawValue(s); } }
然后将其应用于您的类型,如下所示:
public class Employee { public int EmpId { get; set; } public string EmpName { get; set; } // **Note** : I'm not using List<Address> data type for Address, instead of I want list of address in JSON string [JsonConverter(typeof(RawConverter))] public string Address { get; set; } } public class RootObject { public List<Employee> Employees { get; set; } }
样品提琴。
请注意,原始JSON字符串 必须 代表有效的JSON。如果不是,则创建的JSON将不可读。如果要保证JSON文字有效,则可以在内部将JSON保持为已解析状态:
public class Employee { public int EmpId { get; set; } public string EmpName { get; set; } [JsonProperty("Address")] JToken AddressToken { get; set; } [JsonIgnore] public string Address { get { if (AddressToken == null) return null; return AddressToken.ToString(Formatting.Indented); // Or Formatting.None if you prefer } set { if (value == null) AddressToken = null; else // Throw an exception if value is not valid JSON. AddressToken = JToken.Parse(value); } } }
此实现不需要转换器。