简体   繁体   English

C#中的Foreach Json对象

[英]Foreach Json Object in c#

I'm using Json library created by Daniel Crenna. 我正在使用Daniel Crenna创建的Json库。

I have a string json document: 我有一个字符串json文档:

{
    "id": "00132",
    "items":[
        {
           "name":"papers"
        },
        {
           "name":"glasses"
        }
    ]
}

I deserialize it, and if i want to access "id" , i can do: 我反序列化它,并且如果我想访问“ id”,我可以做:

Console.WriteLine(myjsonvar.id);

But if i try to foreach "items" property: 但是,如果我尝试foreach“项目”属性:

foreach(var item in myjsonvar.items){
    Console.WriteLine(item.ToString());
} 

It displays: "System.Collections.Generic.Dictionary'2[System.String, System.Object]" 它显示: “ System.Collections.Generic.Dictionary'2 [System.String,System.Object]”

If i do another foreach inside this one: 如果我在这个里面做另一个foreach:

 foreach(var item in myjsonvar.items){
        foreach(var properties in item){
            Console.WriteLine(properties);
        }
  }

I'm getting " [name, papers] " 我得到“ [姓名,论文]

How can i do to access properties like: 我该如何访问以下属性:

 foreach(var item in myjsonvar.items){
        var itemName = item.name;
  }

Thank you for your responses. 谢谢你的回复。

Since items is an array of dictionaries, your item variable is a dictionary and you can try accessing objects in it using the indexer [] : 由于items是字典数组,因此您的item变量是字典,您可以尝试使用索引器[]来访问其中的对象:

var itemName = item["name"];  // returns "papers", "glasses", etc.

What you pass in to the indexer is the key (property name) and what is returned is the value. 您传递给索引器的是密钥(属性名称),返回的是值。

Note that the property in your JSON object can be a string, integer, boolean, another object, or an array, which is why the value of the dictionary is System.Object . 请注意,JSON对象中的属性可以是字符串,整数,布尔值,另一个对象或数组,这就是字典的值为System.Object It's up to you to cast it to its underlying type. 由您决定将其强制转换为其基础类型。 In this case, item["name"].ToString() should work. 在这种情况下, item["name"].ToString()应该起作用。

Read more here: Dictionary Class 在此处阅读更多内容: 词典类

What you're trying to do is deserialize your json string. 您想要做的是反序列化 json字符串。 In C#, any object has the ToString() method, which basically returns the type of the object as a string. 在C#中, 任何对象都具有ToString()方法,该方法基本上将对象的类型作为字符串返回。 This means that what you see: System.Collections.Generic.Dictionary'2[System.String, System.Object] , is the result of an object of type Dictionary<string, object> 's execution of its ToString() method. 这意味着您看到的是: System.Collections.Generic.Dictionary'2[System.String, System.Object]是对Dictionary<string, object>类型的Dictionary<string, object>执行其ToString()方法的结果。

The reason why that library is converting that part of the json string to a dictionary, is because you do not provide it with a type it should convert to (or maybe it converts any object to a dictionary, I don't know which library you're using). 该库将json字符串的那部分转换为字典的原因是,因为您没有提供应转换为json的类型(或者可能将任何对象都转换为字典,所以我不知道您使用哪个库正在使用)。

If you can specify the type the library should convert your json to, you should create a class like: 如果可以指定库应将json转换为的类型,则应创建一个类似以下的类:

public class DeserializedResult {
    public int Id { get; set; }
    public List<string> Items { get; set; }
    //you can also choose to use a dictionary if you want to keep the key "names"
    //public List<Dictionary<string, string>> Items { get; set; }
}

The library will probably compare the property names with the keys of the json string, and deserialize the data accordingly. 该库可能会将属性名称与json字符串的键进行比较,并相应地反序列化数据。

If your json string would have another key next to name, let's say 'age', then you should probably create a class that represents the data inside the items: 如果您的json字符串的名称旁边有另一个键,假设为“ age”,那么您可能应该创建一个表示项目内部数据的类:

public class Person {
    public string Name { get; set; }
    public int Age { get; set; }
}

Then in your DeserializedResult , Items would be: 然后在您的DeserializedResultItems将是:

public List<Person> Items { get; set;}

Please apply my solution . 请应用我的解决方案。

Create class for you json . 为您创建json类。

public class JsonCLass
{
    public string id { get; set; }
    public Item[] items { get; set; }
}

public class Item
{
    public string name { get; set; }
}

And then use follwing code for desirealize json string . 然后使用以下代码对json string进行期望化处理。

string strXmlData = File.ReadAllText("file.txt");//json string

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            JsonCLass Data = serializer.Deserialize<JsonCLass>(strXmlData);

            string Id = Data.id;//Id field

            foreach (Item objitem in Data.items)
            {
                string ab = objitem.name;//Get all item of jsonID .
            }

Thanks . 谢谢 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM