检查响应字符串是 JSON 对象还是 XML?

问题描述 投票:0回答:3

用于检查响应字符串是 JSON 对象还是 XML 的 C# 代码?

我正在尝试这个:

string responseString = jQuery.parseJSON(response.Content.ReadAsStringAsync().Result);

但是如果结果不是有效的 JSON 对象,这将抛出异常。 (在某些情况下,这是为我返回 XML 内容)我想避免异常处理。有没有返回 bool 的方法来检查这是否是有效的 json?

c# json json.net
3个回答
17
投票

检查响应消息的内容类型。

if (response.Content.Headers.ContentType.MediaType == "application/json")
{
    // parse json
}
else
{
    // parse xml
}

您还可以从响应中读取第一个字符。 如果它是一个 XML 内容,你应该找到一个

<
。即使 XML 声明存在与否。


0
投票

在字符串级别:


using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
public static class Extentions
{

    public static bool IsValidJson(this string value)
    {
        try
        {
            var json = JContainer.Parse(value);
            return true;
        }
        catch
        {
            return false;
        }
    }

}

0
投票

用于检查响应字符串是 JSON 还是 XML 的 Swift 代码

if response.mimeType == "application/xml" {
   //XML
} else if response.mimeType == "application/json" {
   //JSON
} else {
   //Other
}

https://developer.apple.com/documentation/foundation/urlresponse/1411613-mimetype

© www.soinside.com 2019 - 2024. All rights reserved.