从json字符串中提取信息,并将其添加到C#中的列表中 [英] Extracting Information from json string and add it to a list in C#

查看:283
本文介绍了从json字符串中提取信息,并将其添加到C#中的列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是json的新手.我需要不同用户的信息,并将它们添加到c#(.net开发)中的 dataGridView dataTable dataSet 中.信息示例为(json有效):

I am new in json. I want information of different users and add them to a dataGridView or dataTable or dataSet in c# (.net development). Information sample is (The json is valid):

{
    "JrPwbApfIHbQhCUmVIoiVJcPYv93": {
        "address": "Jessore",
        "name": "Dev"
    },
    "iBRZAyn8TQTOgKTcByGOvJjL9ZB3": {
        "address": "Bogra",
        "name": "Kumar Saikat"
    }
}

我想要他们这样:

User1 |杰索尔|开发人员

User1 | Jessore | Dev

User2 |博格拉|库玛·赛卡特(Kumar Saikat)

User2 | Bogra | Kumar Saikat

即使我列出所有清单也将有所帮助.

Even it would help if I could make a list for all of them.

我相信我能够通过
反序列化它们(完全不确定) var model = JsonConvert.DeserializeObject<user>(json);

I believe I was able to deserialise them (not sure at all) by
var model = JsonConvert.DeserializeObject<user>(json);

其中用户是一个类.

 public class Item
{

    public string name;
    public string address;

}

来自此问题答案.从本教程中,如果属性已知,我可以获取值.但是在我的情况下,我的属性是未知的((字符串"User1","User2"将是随机的,因为我将从数据库中获取它们).在此问题上的任何帮助和帮助,将不胜感激.先感谢您.

from this question-answer. From this tutorial I am able to get values if property is known. But in my case my property would be unknown, (string "User1","User2" would be random, since I will get them from a database). Any help and light on this matter would be greatly appreciated. Thank you in advance.

推荐答案

您正在查看JSON字典,因此只需将其反序列化即可:

You're looking at a JSON dictionary, so just deserialize it as such:

public static Dictionary<string,Item> ParseJson(string source)
{
    return JsonConvert.DeserializeObject<Dictionary<string,Item>>(source);
}

如果您这样称呼它:

public static void Main()
{
    var input = @"{'JrPwbApfIHbQhCUmVIoiVJcPYv93': {'address': 'Jessore','name': 'Dev' }, 'iBRZAyn8TQTOgKTcByGOvJjL9ZB3': {'address': 'Bogra','name': 'Kumar Saikat'}}";

    var result = ParseJson(input);

    foreach (var r in result)
    {
        Console.WriteLine("Key={0};Name={1};Address={2}", r.Key, r.Value.name, r.Value.address);
    }
}

输出为:

Key=JrPwbApfIHbQhCUmVIoiVJcPYv93;Name=Dev;Address=Jessore
Key=iBRZAyn8TQTOgKTcByGOvJjL9ZB3;Name=Kumar Saikat;Address=Bogra

此示例将列表转储到控制台,但是您可以轻松地修改for循环以将其添加到列表中.

This example dumps the list to the console, but you could easily modify the for loop to add to a list instead.

DotNetFiddle

这篇关于从json字符串中提取信息,并将其添加到C#中的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆