C#-将json格式的数据解析为嵌套的哈希表 [英] C# - parsing json formatted data into nested hashtables

查看:475
本文介绍了C#-将json格式的数据解析为嵌套的哈希表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#处理一些json格式的数据,但是在确定解决问题的正确方法时遇到了一些问题.我的问题是json格式的数据将采用未知格式(我知道这听起来很奇怪,请继续阅读).基本上,json格式的数据将是名称/值对的一些集合,其中值可能是也可能不是嵌套的名称/值对的数组.为了使事情变得更加有趣,名称/值对数组的嵌套可以在广告无限时继续进行.

I’m trying to work with some json formatted data in C#, but, I’m having some problems determining the proper way to approach the problem. My issue is that the json formatted data will be in an unknown format (I know that sounds odd … please read on). Basically, the json formatted data will be some collection of name/value pairs where the values may or may not be arrays of nested name/value pairs. To make things more fun, the nesting of the name/value pair arrays can continue on ad infinitum.

例如: 我可能有一些看起来像……

For example: I might have some data that looks like…

{
    "1": {
        "1.1": {
            "1.1.1": "value1",
            "1.1.2": "value2",
            "1.1.3": "value3"
        },
        "1.2": "value4",
        "1.3": {
            "1.3.1": {
                "1.3.1.1": "value5",
                "1.3.1.2": "value6"
            },
            "1.3.1.2": "value7",
            "1.3.1.3": "value8"
        }
    }
}

不幸的是,我不知道会发生多少嵌套,从技术上讲,我也不知道任何给定消息中将出现哪些名称/值对.

Unfortunately, I don’t know how much nesting is going to occur and technically I don’t know what names/value pairs will be present in any given message.

C#中是否有任何受支持的机制可以使我轻松地将其解析为一组嵌套的hastables?

Is there any supported mechanism in C# that would enable me to easily parse this into a nested set of hastables?

我想按照以下方式做一些事情(请注意,这段代码在语法上不是100%正确的,最好通过递归来完成……但可以理解).

I’d like to do something along the lines of (note this code is not 100% syntactically correct and would better be done via recursion … but it get’s the idea across).

Hashtable ht = [deserialize data method](jsonformattedstring);
foreach (Hashtable nested in ht)
{
    If (nested.count > 1)
        {
        Foreach (hashtable next in nested)
        …
        }
}

推荐答案

我不喜欢.Net Json解析...它偶尔会做一些奇怪的事情.我已经切换到 Json.NET ,这是一个开放源代码库.它有一个不错的JObject对象,可以满足您的需求.

I didn't like the .Net Json parsing...it does some strange things occasionally. I've switched to Json.NET, an open source library. It has a nice JObject object that will do what you need.

这篇关于C#-将json格式的数据解析为嵌套的哈希表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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