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

时间:2019-03-06 20:04:01

标签: c# json deserialization

我有这个JSON字符串,但不确定如何解析其中的值:

has2

我确实成功解析出了“ id”,但不确定如何访问:
CORS
CORS2
CORS3
CORS4

我得到了错误:
“无法将当前JSON对象(例如{“ name”:“ value”})反序列化为类型'System.String []',因为该类型需要JSON数组(例如[1,2,3])

我已将JSON粘贴到pastebin中: https://pastebin.com/iWgGV9VK

我拥有的代码:

public void getInfo()
{
    String JSONstring = "{ id: 'hello', name: 'Hello',has:{ CORS: false,CORS2: true},has2:{ CORS3: false,CORS4: true}}"; 
    String id = ""; List<String> has = new List<String>(); List<String> has2 = new List<String>();

    var deserializedTicker = JsonConvert.DeserializeObject<JsonInfo>(JSONstring);
    id = deserializedTicker.id; 
    has = deserializedTicker.has.ToList();
    has2 = deserializedTicker.has.ToList();
}

public class JsonInfo
{
    public String id { get; set; }
    public String[] has { get; set; }
    public String[] has2 { get; set; }
}

我正在尝试使用对象的动态方法,但在这里也会出现错误:

''Newtonsoft.Json.Linq.JValue'不包含'id'的定义

//responseBody holds the JSON string
            dynamic stuff = JsonConvert.DeserializeObject(responseBody);
            foreach (var info in stuff)
            {   
                dynamic id = info.Value.id; //''Newtonsoft.Json.Linq.JValue' does not contain a definition for 'id''
                dynamic has = info.Value.has;
                dynamic has2 = info.Value.has2;
                if (has != null && has2 != null)
                {
                    dynamic cors = has.CORS;
                    if(cors != null)
                    {
                        MessageBox.Show(cors.ToString());
                    }
                }
            }

3 个答案:

答案 0 :(得分:2)

首先,让我们更正您的JSON:

{ 
  "id": "hello", 
  "name": "Hello",
  "has": { 
    "CORS": false,
    "CORS2": true
  },
  "has2": { 
    "CORS3": false,
    "CORS4": true
  }
}

现在,您遇到的问题是因为您试图将"has""has2"中的值反序列化为数组。在JSON中,它们不是数组。他们是对象。这样,您需要定义具有相同属性的新类,以便可以正确地反序列化JSON:

public class JsonInfo 
{
  public string id { get; set; }
  public string name { get; set; }
  public JsonHasInfo has { get; set; }
  public JsonHas2Info has2 { get; set; }
}

public class JsonHasInfo
{
  public bool CORS { get; set; }
  public bool CORS2 { get; set; }
}

public class JsonHas2Info
{
  public bool CORS3 { get; set; }
  public bool CORS4 { get; set; }
}

现在您应该能够正确反序列化(正确的)JSON:

String JSONstring = "{ \"id\": \"hello\", \"name\": \"Hello\", \"has\": { \"CORS\": false, \"CORS2\": true }, \"has2\": { \"CORS3\": false, \"CORS4\": true } }\";"
var deserializedTicker = JsonConvert.DeserializeObject<JsonInfo>(JSONstring);

答案 1 :(得分:1)

您的json不正确,键has包含无字典列表。

您需要将反序列化更改为字典或更改json。

在这里您可以看到一个示例: https://json-schema.org/understanding-json-schema/reference/array.html#array

答案 2 :(得分:0)

在您的JSON中,has是一个对象,而不是数组。您应该对类建模,以支持包含属性CORSCORS2等的对象,依此类推。

编辑:如果要坚持使用has作为数组,则应更改JSON以匹配数组期望的内容,例如:has: [ false, true ],并省略CORS内容。 / p>