将JSON输出转换为表格格式 [英] Taking JSON output into table format

查看:354
本文介绍了将JSON输出转换为表格格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从JSON文件中获取解析出的值,并将其转换为行.我已经整周尝试了,但仍然无法解决.

I am trying to take the values I have parsed from a JSON file and convert them into rows. I have tried all week, but still cannot figure this out.

我当前的输出如下:

a: 1
b: 2
c: 3
a: 1a
b: 2a
c: 3a
a: 1b
b: 2b
c: 3b

我希望输出是这样,但找不到解决方案.

I want my output to be like this, but I cannot find a solution.

a   b   c 
1   2   3
1a  2a  3a
1b  2g  3b


using System;
using Newtonsoft.Json;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        string json = 
        @"{
            'somethingone': 'abc',
            'somethingtwo': 'abcde-1234',
            'information': 
            {
                'report': [
                     {
                        'a': '1',
                        'b': '2',
                        'c': '3'
                     },
                     {
                        'a': '1a',
                        'b': '2a',
                        'c': '3a'
                     },
                     {
                        'a': '1b',
                        'b': '2b',
                        'c': '3b'
                     },
                 ]
             }
        }";

        RootObj mainObj = JsonConvert.DeserializeObject<RootObj>(json);

        Console.WriteLine("somethingone: " + mainObj.somethingone);
        Console.WriteLine("somethingtwo: " + mainObj.somethingtwo);

        foreach (Dictionary<string, string> report in mainObj.information.report)
        {
            foreach (KeyValuePair<string, string> item in report)
            {
                string key = item.Key;
                string value = item.Value;

                Console.WriteLine(key + ": " + value);
            }
        }
    }
}

class RootObj
{
    public string somethingone { get; set; }
    public string somethingtwo { get; set; }
    public Information information { get; set; }
}

class Information
{
    public Dictionary<string, string>[] report { get; set; }
}

推荐答案

与只将解析后的json直接转换为DataTable一样,您仅需一行代码即可将json转换为表格式

You can convert your json to table format with only one line of code than can convert your parsed json to DataTable directly like

DataTable dt = jToken["information"]["report"].ToObject<DataTable>();

因此您可以同时利用JTokenDataTable来将json反序列化为直接插入表之类的

So you can take advantage of JToken and DataTable together to deserialize your json to directly into table like

JToken jToken = JToken.Parse(json);

DataTable dt = jToken["information"]["report"].ToObject<DataTable>();

Console.WriteLine("a \t b \t c");
Console.WriteLine("-------------------");

foreach (DataRow dr in dt.Rows)
{
     Console.WriteLine($"{dr["a"]} \t {dr["b"]} \t {dr["c"]}");
}

Console.ReadLine();

输出:

现场演示

这篇关于将JSON输出转换为表格格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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