相关疑难解决方法(0)

以"TryParse"方式反序列化json

当我向服务发送请求(我不拥有)时,它可能会响应请求的JSON数据,或者出现如下错误:

{
    "error": {
        "status": "error message",
        "code": "999"
    }
}
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,HTTP响应代码都是200 OK,所以我不能用它来确定是否有错误 - 我必须反序列化要检查的响应.所以我有一些看起来像这样的东西:

bool TryParseResponseToError(string jsonResponse, out Error error)
{
    // Check expected error keywords presence
    // before try clause to avoid catch performance drawbacks
    if (jsonResponse.Contains("error") &&
        jsonResponse.Contains("status") &&
        jsonResponse.Contains("code"))
    {
        try
        {
            error = new JsonSerializer<Error>().DeserializeFromString(jsonResponse);
            return true;
        }
        catch
        {
            // The JSON response seemed to be an error, but failed to deserialize.
            // Or, it may be a successful JSON response: do nothing.
        } …
Run Code Online (Sandbox Code Playgroud)

.net c# json

56
推荐指数
4
解决办法
5万
查看次数

针对JSON Schema C#验证JSON

有没有办法根据该结构的JSON模式验证JSON结构?我看了,发现JSON.Net验证,但这不符合我的要求.

JSON.net做:

JsonSchema schema = JsonSchema.Parse(@"{
  'type': 'object',
  'properties': {
    'name': {'type':'string'},
    'hobbies': {'type': 'array'}
  }
}");

JObject person = JObject.Parse(@"{
  'name': 'James',
  'hobbies': ['.NET', 'LOLCATS']
}");

bool valid = person.IsValid(schema);
// true
Run Code Online (Sandbox Code Playgroud)

这证实为真.

JsonSchema schema = JsonSchema.Parse(@"{
  'type': 'object',
  'properties': {
    'name': {'type':'string'},
    'hobbies': {'type': 'array'}
  }
}");

JObject person = JObject.Parse(@"{
  'surname': 2,
  'hobbies': ['.NET', 'LOLCATS']
}");

bool valid = person.IsValid(schema);
Run Code Online (Sandbox Code Playgroud)

这也证实了这一点

JsonSchema schema = JsonSchema.Parse(@"{
  'type': 'object',
  'properties': {
    'name': {'type':'string'},
    'hobbies': {'type': 'array'}
  }
}"); …
Run Code Online (Sandbox Code Playgroud)

c# validation json jsonschema

16
推荐指数
1
解决办法
3万
查看次数

标签 统计

c# ×2

json ×2

.net ×1

jsonschema ×1

validation ×1