在使用Json.NET进行序列化时,我需要在反序列化之前取消转义后转义嵌入式JSON。这意味着我根据this的帖子对JSON进行了转义。
这是我的JSON:
{
"Message":null,
"Error":false,
"VData":{
"RNumber":null,
"BRNumber":"Session1"
},
"onlineFields":{
"CCode":"Web",
"MNumber":"15478655",
"Product":"100",
"JsonFile":" {
\"evaluation\":{
\"number\":[
{
\"@paraID\":\"1000\",
\"@Value\":\"\",
\"@label\":\"We are america\"
},
{
\"@paraID\":\"2000\",
\"@Value\":\"100\",
\"@label\":\"We are japan\"
},
{
\"@paraID\":\"3000\",
\"@Value\":\"1000\",
\"@label\":\"We are UK\"
},
{
\"@paraID\":\"4000\",
\"@Value\":\"\",
\"@label\":\"We are China\"
}
]
}
} "
}
}
转义后,将上面的JSON绑定到我的模型类。并且它正常工作。将JSON绑定到我使用以下代码的模型。
private static void showJSON(string testJson){
Response response = JsonConvert.DeserializeObject<Response>(testJson);
var dropdowns = response.OnlineFields.JsonFile;
string json = JsonConvert.SerializeObject(dropdowns, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
}
将JSON绑定到模型后,可以使用一些逻辑将值设置为JSON并返回未转义的JSON。这意味着它还返回未转义的JsonFile
,我再次需要上述JSON格式(转义的嵌入式JsonFile
)发送给客户端API。
这是未转义的JSON格式,我需要将其转换为上述转义的JSON(转义的嵌入式JsonFile
)
{
"Message":null,
"Error":false,
"VData":{
"RNumber":null,
"BRNumber":"Session1"
},
"onlineFields":{
"CCode":"Web",
"MNumber":"15478655",
"Product":"100",
"JsonFile":{
"evaluation":{
"number":[
{
"@paraID":"1000",
"@Value":"",
"@label":"We are america"
},
{
"@paraID":"2000",
"@Value":"100",
"@label":"We are japan"
},
{
"@paraID":"3000",
"@Value":"1000",
"@label":"We are UK"
},
{
"@paraID":"4000",
"@Value":"",
"@label":"We are China"
}
]
}
}
}
}
之前,我问过question如何直接将这种嵌入的JSON反序列化为c#类,但是那里的答案并未说明如何以相同的格式重新序列化。我需要将先前问题的答案扩展到写作。
答案 0 :(得分:1)
您可以通过覆盖this answer并进行嵌套序列化,将EmbeddedLiteralConverter<T>
从How do I convert an escaped JSON string within a JSON object?扩展到 JsonConverter.WriteJson()
,然后像这样写结果字符串文字:
public class EmbeddedLiteralConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
using (new PushValue<bool>(true, () => Disabled, (canWrite) => Disabled = canWrite))
{
using (var sw = new StringWriter(writer.Culture))
{
// Copy relevant settings
using (var nestedWriter = new JsonTextWriter(sw)
{
DateFormatHandling = writer.DateFormatHandling,
DateFormatString = writer.DateFormatString,
DateTimeZoneHandling = writer.DateTimeZoneHandling,
StringEscapeHandling = writer.StringEscapeHandling,
FloatFormatHandling = writer.FloatFormatHandling,
Culture = writer.Culture,
// Remove if you don't want the escaped \r\n characters in the embedded JSON literal:
Formatting = writer.Formatting,
})
{
serializer.Serialize(nestedWriter, value);
}
writer.WriteValue(sw.ToString());
}
}
}
[ThreadStatic]
static bool disabled;
// Disables the converter in a thread-safe manner.
bool Disabled { get { return disabled; } set { disabled = value; } }
public override bool CanWrite { get { return !Disabled; } }
public override bool CanRead { get { return !Disabled; } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var contract = serializer.ContractResolver.ResolveContract(objectType);
if (contract is JsonPrimitiveContract)
throw new JsonSerializationException("Invalid type: " + objectType);
if (existingValue == null)
existingValue = contract.DefaultCreator();
if (reader.TokenType == JsonToken.String)
{
var json = (string)JToken.Load(reader);
using (var subReader = new JsonTextReader(new StringReader(json)))
{
// By populating a pre-allocated instance we avoid an infinite recursion in EmbeddedLiteralConverter<T>.ReadJson()
// Re-use the existing serializer to preserve settings.
serializer.Populate(subReader, existingValue);
}
}
else
{
serializer.Populate(reader, existingValue);
}
return existingValue;
}
}
struct PushValue<T> : IDisposable
{
Action<T> setValue;
T oldValue;
public PushValue(T value, Func<T> getValue, Action<T> setValue)
{
if (getValue == null || setValue == null)
throw new ArgumentNullException();
this.setValue = setValue;
this.oldValue = getValue();
setValue(value);
}
#region IDisposable Members
// By using a disposable struct we avoid the overhead of allocating and freeing an instance of a finalizable class.
public void Dispose()
{
if (setValue != null)
setValue(oldValue);
}
#endregion
}
然后,在反序列化和序列化时,将转换器添加到JsonSerializerSettings.Converters
:
var settings = new JsonSerializerSettings
{
Converters = { new EmbeddedLiteralConverter<JsonFile>() },
};
var response = JsonConvert.DeserializeObject<Response>(testJson, settings);
var json2 = JsonConvert.SerializeObject(response, Formatting.Indented, settings);
或者,您可以使用JsonConverterAttribute
将转换器直接应用于模型,如下所示:
public class OnlineFields
{
public string CCode { get; set; }
public string MNumber { get; set; }
public string Product { get; set; }
[JsonConverter(typeof(EmbeddedLiteralConverter<JsonFile>))]
public JsonFile JsonFile { get; set; }
}
注意:
严格来讲,您输入的JSON格式不正确。属性JsonFile
的字符串值包含未转义的回车符:
"JsonFile":" {
\"evaluation\":{
\"number\":[
根据original JSON proposal和JSON RFC 7159 Page 8,必须转义这样的控制字符 :
"{\r\n \"evaluation\": {\r\n \"number\": ..."
要确认这一点,您可以将初始JSON上传到https://jsonformatter.curiousconcept.com/,它会报告以下错误:
无效的JSON(RFC 4627):错误:找到了无效的字符。[代码18,结构39]
事实证明,Json.NET会毫无抱怨地读取此类无效的JSON,但只会通过正确转义嵌套的JSON文字内的回车符和换行符来编写格式正确的JSON。因此,重新序列化的JSON看起来与初始JSON并不相同。但是,它将格式正确,并且可以由任何JSON解析器使用。
为防止序列化时出现堆栈溢出异常,当使用从this answer到 JSON.Net throws StackOverflowException when using [JsonConvert()] 的技术递归调用EmbeddedLiteralConverter<T>.WriteJson()
时,将禁用自身。 / p>
工作示例.Net小提琴here。