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

时间:2016-11-18 10:54:56

标签: c# get json.net

我得到了JSON,我需要从中提取少量数据。

{  
 "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对象反序列化为一个成功的动态对象。我正在使用以下C#代码进行工作

string responseText = reader.ReadToEnd();
dynamic in_values =    JsonConvert.DeserializeObject(responseText);
string state = in_values.state;

如果你能看到我在JSON字符串中有一些带连字符的标签名称。

例如output-parameters

我无法使用点操作,因为它会像跟随

一样
in_values.output-parameters;

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

1 个答案:

答案 0 :(得分:1)

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

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;