Deserialize json in a “TryParse” way

后端 未结 6 643
走了就别回头了
走了就别回头了 2020-11-28 09:14

When I send a request to a service (that I do not own), it may respond either with the JSON data requested, or with an error that looks like this:

{
    \"er         


        
6条回答
  •  醉酒成梦
    2020-11-28 09:41

    To test whether a text is valid JSON regardless of schema, you could also do a check on the number of quotation marks:" in your string response, as shown below :

    // Invalid JSON
    var responseContent = "asgdg"; 
    // var responseContent = "{ \"ip\" = \"11.161.195.10\" }";
    
    // Valid JSON, uncomment to test these
    // var responseContent = "{ \"ip\": \"11.161.195.10\", \"city\": \"York\",  \"region\": \"Ontartio\",  \"country\": \"IN\",  \"loc\": \"-43.7334,79.3329\",  \"postal\": \"M1C\",  \"org\": \"AS577 Bell Afgh\",  \"readme\": \"https://ipinfo.io/missingauth\"}";
    // var responseContent = "\"asfasf\"";
    // var responseContent = "{}";
    
    int count = 0;
    foreach (char c in responseContent)
        if (c == '\"') count++; // Escape character needed to display quotation
    if (count >= 2 || responseContent == "{}") 
    {
        // Valid Json
        try {
            JToken parsedJson = JToken.Parse(responseContent);
            Console.WriteLine("RESPONSE: Json- " + parsedJson.ToString(Formatting.Indented));
        }  
        catch(Exception ex){
            Console.WriteLine("RESPONSE: InvalidJson- " + responseContent);
        }
    }
    else
        Console.WriteLine("RESPONSE: InvalidJson- " + responseContent);
    

提交回复
热议问题