简体   繁体   English

在C#中从JSON提取变量数据

[英]Extracting variable data from JSON in C#

I have the following JSON which I need to manipulate into a different JSON format to be consumed by another process. 我有以下JSON,我需要将其处理为不同的JSON格式,以供其他进程使用。 My data is variable to some extent. 我的数据在某种程度上是可变的。 Here is an example: 这是一个例子:

{
    "subform_12": {
        "multiline_2": "Subform 1 Long Text",
        "listpicker_5": "High",
        "alpha_1": "SubForm 1 Text"
    },
    "subform_13": {
        "multiline_2": "Subform 2 Long Text",
        "alpha_1": "SubForm 2 Text"
    }
}

The variable part is the name of the json object (eg "subform_13") and the number and content of name pairs per object (eg "multiline_2": "Subform 1 Long Text"). 可变部分是json对象的名称(例如“ subform_13”)以及每个对象的名称对的数量和内容(例如“ multiline_2”:“ Subform 1 Long Text”)。

What I need to do is convert each node into its own chunk of json, as in the following format: 我需要做的是将每个节点转换为自己的json块,格式如下:

{
    "subform_13": [
        [{
                "fieldKey": "multiline_2",
                "value": "Subform 2 Long Text"
            },
            {
                "fieldKey": "alpha_1",
                "value": "SubForm 2 Text"
            }
        ]
    ]
}

Then separately: 然后分别:

    {
    "subform_13": [
        [{
                "fieldKey": "multiline_2",
                "value": "Subform 2 Long Text"
            },
            {
                "fieldKey": "alpha_1",
                "value": "SubForm 2 Text"
            }
        ]
    ]
}

So far I see that I can iterate thru the list as follows: 到目前为止,我看到可以遍历列表,如下所示:

     var json = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(
            jsonString,
            new Newtonsoft.Json.JsonSerializerSettings()
            {
                DateParseHandling = Newtonsoft.Json.DateParseHandling.None,
            });

    foreach (var item in json)
    {
       // I can see the "subform_13" and contents here in item , how do I generically extract them?
    }

Any help appreciated. 任何帮助表示赞赏。

Here is your Main method augmented with the ability to iterate through all values: 这是您的Main方法,具有迭代所有值的能力:

    static void Main(string[] args)
    {
        var json = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,JObject>>(
            jsonString,
            new Newtonsoft.Json.JsonSerializerSettings()
            {
                DateParseHandling = Newtonsoft.Json.DateParseHandling.None,
            });
        foreach (var item in json)
        {
            var key = item.Key; // "subform_12"
            var val = item.Value;
            Console.WriteLine(key+":");
            foreach (var field in val)
            {
                var fieldKey = field.Key; // e.g. "multiline_2"
                var fieldVal = field.Value; // e.g. "Subform 1 Long Text"

                Console.WriteLine($"{fieldKey}={fieldVal.Value<string>()}");                    
            }
            Console.WriteLine();
        }
    }

I am just printing the values out; 我只是打印出值; you would construct your new objects - for example as dynamic - using these values. 您将使用这些值构造新对象(例如, dynamic对象)。

The output of my Main is: 我的Main的输出是:

subform_12:
multiline_2=Subform 1 Long Text
listpicker_5=High
alpha_1=SubForm 1 Text

subform_13:
multiline_2=Subform 2 Long Text
alpha_1=SubForm 2 Text

Hope it helps. 希望能帮助到你。

There are probably more elegant ways using linq, but here's code using a plain old JavaScriptSerializer from System.Web.Extensions. 可能有使用linq的更优雅的方法,但是这里的代码使用了System.Web.Extensions中简单的旧JavaScriptSerializer。

There is a result dictionary, which you probably don't need if you want each object separated. 有一个结果字典,如果希望每个对象都分开,则可能不需要。

The json strings for each object is stored in the allJson list. 每个对象的json字符串存储在allJson列表中。

Similary, if you want the dictionary objects themselves you could just add seperated to a list during each iteration. 类似地,如果您想要字典对象本身,则可以在每次迭代期间将分隔符添加到列表中。

        string s = "{\"subform_12\":{\"multiline_2\":\"Subform 1 Long Text\",\"listpicker_5\":\"High\",\"alpha_1\":\"SubForm 1 Text\"},\"subform_13\":{\"multiline_2\":\"Subform 2 Long Text\",\"alpha_1\":\"SubForm 2 Text\"}}";
        JavaScriptSerializer ser = new JavaScriptSerializer();
        Dictionary<string, object> obj = ser.DeserializeObject(s) as Dictionary<string, object>;

        // combined dictionary of all results
        Dictionary<string, object> result = new Dictionary<string, object>();
        // an intermediary dictionary to house the results of each object
        Dictionary<string, object> separated = new Dictionary<string, object>();

        // a list to hold the json representation of each separate object
        List<String> allJson = new List<string>();
        foreach (KeyValuePair<string, object> src in obj)
        {
            Dictionary<string, object> children = (Dictionary<string, object>)src.Value;
            Dictionary<string, object> t = new Dictionary<string, object>();
            separated = new Dictionary<string, object>();
            List<object> l = new List<object>();
            foreach (KeyValuePair<string, object> child in children)
            {
                t.Add("fieldKey", child.Key);
                t.Add("value", child.Value);
                l.Add(t);
                t = new Dictionary<string, object>();
            }
            separated.Add(src.Key, l.ToArray());
            allJson.Add(ser.Serialize(separated));
            result.Add(src.Key, l.ToArray());
        }

        // final string containing all transformed objects combined.            
        string combined = ser.Serialize(result);

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

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