使用C#访问复杂的JSON内部对象反序列化 [英] Access complex JSON inner objects deserilization using c#

查看:162
本文介绍了使用C#访问复杂的JSON内部对象反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个COMPLEX JSON,我需要对它进行反序列化并访问其所有对象.我的JSON看起来像这样

I have a COMPLEX JSON which I need to deserialize and access all its objects. My JSON looks like this

{
    "name": {},
    "percentage": [
        {
            "math": {
                "2.503300099.1": 460800,
                "2.503300099.2": 460800,
                "2.503300099.3": 460800,
                "2.503308292.1": 2457600,
                "2.503308292.2": 2457600,
                "2.503308292.3": 2457600
            },
            "english": {
                "2.503300099": "hello",
                "2.503308292": "hi"
            },

            "exam": "2.0"
        }
    ],
    "class": {},
    "section": "7.17.1",
    "total": 1
}

JSON的值可能会更改,它们出现的次数也可能会更改.

The values of JSON may change, number of times they appear may also change.

到目前为止,我可以访问的是名称,类,节,总数,而问题是百分比.我也可以达到百分比,但是我无法使用数学或英语,也无法使用其值进行考试.

What I can access so far is name,class,section,total,and issue is with percentage part. I can reach till percentage also but I cant access math or English, or exam with their values.

string content = await response.Content.ReadAsStringAsync();                 
  JObject Search = JObject.Parse(content);                  
  Speed res = new Speed();

res.class= Search["class"].ToString();  // good
res.english = Search["english"].ToString();// not good

请提供任何帮助或建议吗?

Any help or suggestion please ?

编辑

在对JSON的结构提出了如此多的问题之后,我想澄清一下该结构不会改变,但是对象的数量可能会发生变化,让我们举一个例子来了解这一点:

After so many questions of the structure of JSON, I would like to clarify that structure wont changes ever but the number of objects may, lets understand this with an example:

{
    "One": {},
    "Two": [
        {
            "twoA": {
                "2.503300099.1": 460800,
                "2.503300099.2": 460800,
                 "...." : ...,
                 "...." : ...,
            },
            "TwoB": {
                "2.503300099": "value",
                "2.503308292": "value"
                "...." : ...,
                "...." : ...,
            },
             "TwoC": {
                "2.503300099": "value",
                "2.503308292": "value"
                "...." : ...,
                "...." : ...,
            },
            "exam": "2.0",
            "...." : ...,
            "...." : ...,
        }
    ],
    "Three": {empty},
    "Four": "value string",
    "Five": value int
    .....
    .....
}

希望这澄清了对JSON结构的疑问

Hope this clarifies doubt on JSON structure

推荐答案

从对您的问题和后续答案的评论来看,似乎API的数据难以预测,以至于我开始争论人们负责该API的用户应退后一步,重新考虑他们的方法.我看不到如何解析任何数据,而又没有足够暗示如何构造数据.

Judging from the comments on your question and subsequent answers it would seem that the data from the API is unpredictable to the extent that I'd begin arguing that the people responsible for that API should take a step back and rethink their approach. I don't see how you could ever parse any data without as much as hint as to how that data might be structured.

但也许我反应过度...

But maybe I'm overreacting...

也许您正在寻找将数据解析为dynamic的答案?使用这种方法,您可以执行以下操作:

Maybe parsing the data as a dynamic is the answer you're looking for? Using this approach, you can do things like:

const string data = "{\"1123.5433\":{\"42.42.42\":\"bazinga\"}}";
var myDynamic = JsonConvert.DeserializeObject<dynamic>(data);

Console.WriteLine(myDynamic["1123.5433"]["42.42.42"]); // -> bazinga;

在您的示例中,math中的值的路径,如果我没有记错的话,将类似于:

The path for a value in math in your example, if I'm not mistaken, would be something like:

myDynamic["percentage"][0]["math"]["2.503300099.1"]; // ~ 460800?

虽然不是很可读.还是稳定的.所以,我住了,回想起我最初的困惑,即生物是如何思考所讨论的API的……

Not very readable though. Or stable. So, I reside, back to ponder my original quandary of what manner of creature thought up the API in question...

编辑:更新以反映评论和原始问题的更改:

Updates to reflect comments and changes in the original question:

// First example
const string originalExample =
    "{\"name\": {},\"percentage\": [{\"math\": {\"2.503300099.1\": 460800,\"2.503300099.2\": 460800},\"english\": {\"2.503300099\": \"hello\"}}]}";
var myFirstDynamic = JsonConvert.DeserializeObject<dynamic>(originalExample);

Console.WriteLine(myFirstDynamic["percentage"][0]["math"]["2.503300099.1"]); // -> 460800

// Second example
const string newExample =
            "{\"One\": {},\"Two\": [{\"twoA\": {\"2.503300099.1\": 460800,\"2.503300099.2\": 460800,},\"TwoB\": {\"2.503300099\": \"value\",\"2.503308292\": \"value\"},\"TwoC\": {\"2.503300099\": \"value\",\"2.503308292\": \"value\"},\"exam\": \"2.0\"}]}";
var mySecondDynamic = JsonConvert.DeserializeObject<dynamic>(newExample);

Console.WriteLine(mySecondDynamic["Two"][0]["twoA"]["2.503300099.1"]); // -> 460800;

鉴于您在第二个示例中提供的结构,您还可以定义合适的类型以适合相同的结构:

Given the structure you present in your second example, you could also define suitable types to fit that same structure:

public class MyObject
{
    public IEnumerable<MyNextObject> Two { get; set; }
}

public class MyNextObject
{
    public dynamic twoA { get; set; }
}

然后您可以像这样反序列化和解析:

Then you can deserialize and parse like this:

var deserializedToType = JsonConvert.DeserializeObject<MyObject>(newExample);
Console.WriteLine(deserializedToType.Two.First().twoA["2.503300099.1"]); // -> 460800;

由于源数据中的属性名称对于C#无效,因此您仍然需要在可能会出现问题的位置(例如MyNextObject.twoA)键入dynamic.另外,根据您要尝试执行的操作以及在何种情况下,枚举percentage等的子级可能比选择特定索引更好.

Because the property names in the source data are not valid for C#, you still need the dynamic typing in those places where problems would otherwise occur (e.g. MyNextObject.twoA). Also, depending on what you're trying to do and in what context, enumerating the children of percentage etc. may be a better choice than going for specific indexes.

请注意,我使用的是与您在所有示例中介绍的json结构完全相同的json结构,尽管为了简洁起见,最后简化了说明,并转而提出了可行的示例.

Note that I'm using the exact same json structure as you presented in all my examples, albeit shortened in the end for brevity and escaped to present working examples.

如果源属性名称不一致,无效或不遵循通用惯例,为了保持C#代码干净,您可能应该使用某种在源和目标之间映射值的方法.例如.如果您使用的是Json.NET,则类似JsonProperty属性.

Where your source property names are inconsistent, invalid or not adhering common praxis, to keep your C# code clean, you should probably use some method of mapping values between source and target. E.g. if you're using Json.NET, things like the JsonProperty attribute.

另外,请不要在这里我不提出类似于代码的生产".显然,您应该小心并妥善处理诸如null值或越界索引之类的潜在问题.

Also, please not that I'm not presenting "production like code" here. You should obviously take care and handle potential problems such as null values or out-of-bound indexes properly.

这篇关于使用C#访问复杂的JSON内部对象反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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