2016-11-18 59 views
1

我得到以下JSON,我需要從中提取少量數據。從變量名中帶有特殊標記的JSON字符串獲取值C#

{ 
"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對象中的動態物體在使用下面的工作

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

C#代碼successful.I'm如果你能看到我有一些標籤名稱連字符在JSON字符串中。

例如output-parameters

我不能使用點操作,因爲那會像遵循

in_values.output-parameters; 

如何從JSON字符串中提取這些值。

+0

將其映射到類並使用JsonProperty屬性。 – mybirthname

回答

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; 
相關問題