首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从JSON字符串中获取值,该字符串在变量名称C#中具有特殊标记

从JSON字符串中获取值,该字符串在变量名称C#中具有特殊标记
EN

Stack Overflow用户
提问于 2016-11-18 10:54:55
回答 1查看 649关注 0票数 1

我会跟踪JSON,在这里我需要从JSON中提取很少的数据。

代码语言:javascript
复制
{  
 "id":"400xxtc200",
 "state":"failed",
 "name":"barbaPapa",
 "content-exception":"AccessDenied",
 "input-parameters":[  
    {  
       "value":{  
          "string":{  
             "value":"In"
          }
       },
       "type":"string",
       "name":"Operation",
       "scope":"local"
    },
    {  
       "value":{  
        "string":{  
           "value":"bila"
        }
     },
     "type":"string",
     "name":"VMName",
     "scope":"local"
  },
  {  
     "value":{  
        "string":{  
           "value":"txtc"
        }
     },
     "type":"string",
     "name":"PSUser",
     "scope":"local"
  },
  {  
     "value":{  
        "string":{  
           "value":"dv1"
        }
     },
     "type":"string",
     "name":"Datacenter",
     "scope":"local"
  },
  {  
     "value":{  
        "string":{  
           "value":"tpc"
        }
     },
     "type":"string",
     "name":"ServiceArea",
     "scope":"local"
  },
  {  
     "value":{  
        "string":{  
           "value":"103"
        }
     },
     "type":"string",
     "name":"SQN",
     "scope":"local"
  }
 ],
 "output-parameters":[  
  {  
     "type":"Array/string",
     "name":"tag",
     "scope":"local"
  },
  {  
     "value":{  
        "string":{  
           "value":"AccessDenied"
        }
     },
     "type":"string",
     "name":"Error",
     "scope":"local"
  }
 ]
}

我试图将JSON对象反序列化为一个成功的动态对象。

代码语言:javascript
复制
string responseText = reader.ReadToEnd();
dynamic in_values =    JsonConvert.DeserializeObject(responseText);
string state = in_values.state;

如果您可以看到,我在JSON字符串中有一些带有连字符的标签名。

例如,output-parameters

我不能使用这个点操作,因为这样它就会如下所示

代码语言:javascript
复制
in_values.output-parameters;

如何从JSON字符串中提取这些值。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-18 11:05:54

在这种情况下,您可以使用JsonProperty

代码语言:javascript
复制
public class SampleClass
{
    public string id { get; set; }
    public string state { get; set; }
    public string name { get; set; }

    [JsonProperty(PropertyName = "content-exception")]
    public string content_exception { get; set; }
    [JsonProperty(PropertyName = "input-parameters")]
    public List<InputParameter> input_parameters { get; set; }
    [JsonProperty(PropertyName = "output-parameters")]
    public List<OutputParameter> output_parameters { get; set; }
}

string json = File.ReadAllText("abc.txt");
SampleClass obj = JsonConvert.DeserializeObject<SampleClass>(json);
List<OutputParameter>  ls = obj.output_parameters;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40675292

复制
相关文章

相似问题

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