When serializing with Json.NET, I need to escape embedded JSON after previously unescaping while deserializing. Which means I unescaped following JSON according to this post.
Here is my 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\"
}
]
}
} "
}
}
After unescaping, I bind the above JSON to my model classes. And it works properly. to Bind JSON to a model I used following code.
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);
}
After bind JSON to model, there has some logic to set values to JSON and returns unescaped JSON. which means it also returns unescaped JsonFile
, I again need above JSON format (escaped embedded JsonFile
) to send to the client API.
This is unescaped JSON format, I need convert this to above escaped JSON (escaped embedded 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"
}
]
}
}
}
}
Previously I asked a question for how to directly deserialize such embedded JSON into c# classes, but the answer there did not explain how to re-serialize in the same format. I need to extend the answer from that previous question to writing.