将json的动态属性读取到.net C#中 [英] Reading dynamic attributes of json into .net C#

查看:463
本文介绍了将json的动态属性读取到.net C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击API后,我将得到以下json格式:

I am getting following json format after hitting to an API:

{
    "7407": {
        "survey_id": "406",
        "device_id": "1",
        "response_time": "2013-10-10 16:14:01",
        "timezone": "0",
        "language_id": "en",
        "response_id": "7407",
        "device_alias": "QR Code App",
        "site_name": "QR Code App",
        "country_name": "United States",
        "state_name": "New York",
        "city_name": "Suffern",
        "zip": "",
        "voucher_name": null,
        "voucher_mode": null,
        "surveyee_name": null,
        "surveyee_email": null,
        "surveyee_phone": null,
        "ques": {
            "": []
        }
    },
    "7408": {
        "survey_id": "406",
        "device_id": "1",
        "response_time": "2013-10-10 16:36:56",
        "timezone": "0",
        "language_id": "en",
        "response_id": "7408",
        "device_alias": "QR Code App",
        "site_name": "QR Code App",
        "country_name": "India",
        "state_name": "Gujarat",
        "city_name": "Ahmedabad",
        "zip": "",
        "voucher_name": null,
        "voucher_mode": null,
        "surveyee_name": null,
        "surveyee_email": null,
        "surveyee_phone": null,
        "ques": {
            "": []
        }
    } }

我正在使用 JSON.Net 来读取上述给定的json数据.

I am using JSON.Net to read the above given json data.

要将这些数据映射到.Net代码,我将需要.net中的类,它们的属性名称应与json字符串中的名称相同. 但是 json中有一些可以动态更改的属性(在我的情况下为"7407","7408"等),即,可以根据我们传递给参数的值来更改此值.

To map this data into .Net code, I will need classes in .net, having same properties' name as in json string. BUT there are some attributes in json which can be dynamic ("7407", "7408" etc in my case) i.e. this value can be changed based on what are we passing into parameters.

我的问题是,我们如何将json属性(本质上是动态的,并且可以根据提供给api的参数而具有任何值)映射到.net类?

My question is, how can we map json attributes (which are dynamic in nature and can have any value depending upon the parameters provided to the apis) to our .net class ?

推荐答案

我发现处理此类JSON数据的最佳方法是使用JSON.Net库的JObject类. 例如:

The best way I could find handling this kind of JSON data is by using JObject class of the JSON.Net library. For eg:

Newtonsoft.Json.Linq.JObject jSonObject = JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(somejsonstring);

,然后您就可以遍历或应用其他逻辑来读取jSonObject

and then you can loop through or apply some other logic to read jSonObject

这篇关于将json的动态属性读取到.net C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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