首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >验证Json Keys

验证Json Keys
EN

Stack Overflow用户
提问于 2016-11-21 10:53:44
回答 2查看 49关注 0票数 0

我有以下几点:

代码语言:javascript
复制
{
  "requirements": {
    "-FileName": "sample.xls",
    "requirement": [
      {
        "desc": "Employee status        will be classified as: 
•   Assigned $ when employee is working on a project. 
•   Reserved when employee is scheduled to work on a project in near future. Unassigned when employee is not working on project.",
        "Id": "Req40"
      },
      {
        "Id": "NFR-2",
        "desc": "Team Leader should create resource allocation $% request in Maintain Project Module. Resource allocation request $@is associated with only one role. Project $@ Manager should provide roll-on date and roll-off date in resource allocation request."
      },
      {
        "Id": "req2",
        "desc": "PRMS must always be available except during the & @ scheduled maintenance. Scheduled maintenance must always be at 8PM on week days.",
        "message": "message of Req3"
      }
    ]
  }
}

我想检查它是否包含Id和Desc标签或键。

我试过以下代码:-

代码语言:javascript
复制
try
{                    
    var obj = Newtonsoft.Json.Linq.JToken.Parse(strInput);

    if(obj["Id"]!=null)
    return true;
    else
        return false;
}
catch (JsonReaderException jex)
{
    Logger.GetInstance().LogException(jex, jex.StackTrace, Category.General);
    return false;
}

但是,这段代码将obj" Id“作为null,即使Id存在于Json中。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-11-21 11:03:48

你应该像这样检查你现在的结构。

代码语言:javascript
复制
var id = obj["requirements"]["requirement"][0]["Id"];

if(id != null)
   return true;
else
   return false;
票数 1
EN

Stack Overflow用户

发布于 2016-11-22 11:36:27

你可以使用反射

代码语言:javascript
复制
JavaScriptSerializer serializer = new JavaScriptSerializer();
var obj = serializer.DeserializeObject(json);

var propery = obj.GetType().GetProperty("Id");
if (propery == null)
    return false;
else
    return true;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40718410

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档