Json: how to properly strip the escape characters with json.net

前端 未结 5 887
既然无缘
既然无缘 2020-12-18 22:14

I have json response in the below format.

\"[{\\\\\\\"JobID\\\\\\\":\\\\\\\"1\\\\\\\",\\\\\\\"BillGenerationDate\\\\\\\":\\\\\\\"4/29/2013 2:53:34 PM\\\\\\\         


        
相关标签:
5条回答
  • 2020-12-18 22:23

    For me the code below works

    string contentCorrected = contentCorrected.Replace(**@"\""", ""**);
    
    0 讨论(0)
  • 2020-12-18 22:29

    THE SHORT ANSWER: first you need to deserialize the escaped string, but not to the target CLR type, but deserialize to another string:

    // Initial example json string:  "\"{\\\"Property1\\\":1988,\\\"Property2\\\":\\\"Some data :D\\\"}\""
    
    
    // First, deserialize to another string (unescaped string).
    string unescapedJsonString = JsonConvert.DeserializeObject<string>(escapedJsonString);
    Debug.WriteLine(unescapedJsonString);
    // Prints:
    // "{\"Property1\":1988,\"Property2\":\"Some data :D\"}"
    
    
    // Second, deserialize to another string, again (in this case is necessary)
    var finalUnescapedJsonString = JsonConvert.DeserializeObject<string>(unescapedJsonString);
    Debug.WriteLine(finalUnescapedJsonString);
    // This time prints a final, unescaped, json string:
    // {"Property1":1988,"Property2":"Some data :D"}
    
    
    // Finally, perform final deserialization to the target type, using the last unescaped string.
    MyClass targetObject = JsonConvert.DeserializeObject<MyClass>(finalUnescapedJsonString);
    

    LONG ANSWER (but interesting) Using string.Replace(... could generate an invalid string, because it could damage certain special characters that needed the backslash to be deserialized correctly .

    This type of escaped strings are usually generated when a string that was already a json string, its serialized again (or even more times). This causes something like "various levels of serialization" (it really is a serialization of a string with reserved characters), and the result is backshash characters (or groups of one, two or more backslash followed: \, \\, \\\) scattered all over the string. So, to remove them correctly is not enough to replace them by empty.

    THE RIGHT WAY: A better way to get a unescaped string would be to do a first deserialization to string type (Repeat this several times if necessary), And then do a final deserialization to target CLR type:

    // -- SERIALIZATION --
    
    // Initial object
    MyClass originObj = new MyClass { Property1 = 1988, Property2 = "Some data :D" };
    
    // "First level" Of serialization.
    string jsonString = JsonConvert.SerializeObject(originObj);
    Debug.WriteLine(jsonString);
    // Prints: 
    // {"Property1":1988,"Property2":"Some data :D"}
    
    
    // "Second level" of serialization.
    string escapedJsonString = JsonConvert.SerializeObject(jsonString);
    Debug.WriteLine(escapedJsonString);            
    // "{\"Property1\":1988,\"Property2\":\"Some data :D\"}"
    // Note the initial and final " character and de backslash characters
    
    // ...
    // at this point you could do more serializations ("More levels"), Obtaining as a result more and more backslash followed,
    // something like this:
    // "\"{\\\"Property1\\\":1988,\\\"Property2\\\":\\\"Some data :D\\\"}\""
    // Note that is... very very crazy :D
    // ...
    
    // -- DESERIALIZATION --
    
    // First deserialize to another string (unescaped string).
    string unescapedJsonString = JsonConvert.DeserializeObject<string>(escapedJsonString);
    Debug.WriteLine(unescapedJsonString);
    // Prints:
    // {"Property1":1988,"Property2":"Some data :D"}
    
    // ...
    // at this point you could repeat more deserializations to string, if necessary. For example if you have many backslash \\\
    // ...
    
    // Finally, perform final deserialization to the target type, using the last unescaped string.
    MyClass targetObject = JsonConvert.DeserializeObject<MyClass>(unescapedJsonString);
    
    0 讨论(0)
  • 2020-12-18 22:40

    The problem occurs when valid double quotes are used within the answer. Removing and/or Replacing won't solved this in all cases. It frustrated me too until I found a simple solution:

    var billList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(@contentCorrected);
    
    0 讨论(0)
  • 2020-12-18 22:40
    1. Remove all the "\" character before you deserialize it. Use replace function.

      yourJsonString.Replace("\\\\\", "");

    2. Your Json string is incomplete or doesnot seems to be of type List<Dictionary<string, string>>". Correct the type you want the json to be converted. I modified your json a little as follows and it worked.

      newJson = "{ \"array\":" + yourJsonString + "}"

    0 讨论(0)
  • 2020-12-18 22:46

    Try string contentCorrected = contentCorrected.Replace(@"\", "");before deserialization process.

    0 讨论(0)
提交回复
热议问题