遍历JSON对象和值以在C#中列出

时间:2019-07-09 13:26:57

标签: c# json deserialization

我正在尝试从JSON对象获取值并将其保存到2个列表中。我正在努力了解如何循环遍历JSON对象以获得JSON数组值。

我相信我正在正确反序列化,但是我坚持前进。这是我目前拥有的

JObject jsonResult =  {"foodtype": ["Pizza", "Pasta", "Bread"], 
               "drinks": ["Coke", "Root Beer"]}


 public class Rootobject
  {
    public string[] foodType { get; set; }
    public string[] drinks { get; set; }
  }

var allObject = JsonConvert.DeserializeObject<Rootobject>(jsonResult.ToString());

我想要从JSON结果中生成2个列表,如下所示:

List<string> food = new List<string> {Pizza, Pasta, Bread}
List<string> drink = new List<string> {Coke, Root Beer}

2 个答案:

答案 0 :(得分:1)

您的代码无效,以下代码段不正确:

JObject jsonResult =  {"foodtype": ["Pizza", "Pasta", "Bread"], 
               "drinks": ["Coke", "Root Beer"]}

您需要一个可以反序列化的字符串。

以下代码应为您提供帮助:

static void Main(string[] args)
{
    var objectToSerialize = new Rootobject()
    {
        Drinks = new [] {"Coke", "Root Beer" },
        FoodType = new[] { "Pizza", "Pasta", "Bread" }
    };

    var serializedByTheLib = JsonConvert.SerializeObject(objectToSerialize);

    string jsonResult =
        "{ \"foodtype\": [\"Pizza\", \"Pasta\", \"Bread\"], \"drinks\": [\"Coke\", \"Root Beer\"] }";

    var deserializedObject = JsonConvert.DeserializeObject<Rootobject>(jsonResult);
}


public class Rootobject
{
    [JsonProperty("foodType")]
    public string[] FoodType { get; set; }

    [JsonProperty("drinks")]
    public string[] Drinks { get; set; }
}

关键概念:

  • 对象可以序列化为JSON
  • 可以将JSON字符串反序列化为对象

看看newtonsoft documentation以获得更多信息

答案 1 :(得分:0)

将json字符串反序列化为Rootobject后,您可以选择它的属性:

string json = "{\"foodtype\": [\"Pizza\", \"Pasta\", \"Bread\"], \"drinks\": [\"Coke\", \"Root Beer\"]}";
Rootobject rootObject = JsonConvert.DeserializeObject<Rootobject>(json);
List<string> food = rootObject.foodType.ToList();
List<string> drinks = rootObject.drinks.ToList();