首页 / C#开发 / 正文

[.NET/C#].NET/C#应用程序开发中如何将JSON字符串反序列化成二维数组对象?

3418 1 发布于: 2018-11-08 读完约需8分钟

问题描述

如题,在.NET/C#应用程序开发中,如何将JSON字符串反序列化成二维数组对象?JSON字符串形如:

var json = "[[100,"美元","696.7","人民币"],[100,"欧元","789.23","人民币"]]";

当前具体的待转换的JSON字符串如:

[[100,"美元","696.7","人民币"],[100,"欧元","789.23","人民币"],[100,"日元","6.1782","人民币"],[100,"港元","88.826","人民币"],[100,"英镑","891.04","人民币"],[100,"人民币","59.996","林吉特"],[100,"人民币","943.01","卢布"],[100,"澳元","493.89","人民币"],[100,"加元","529.98","人民币"],[100,"新西兰元","455.05","人民币"],[100,"新加坡元","503.4","人民币"],[100,"瑞士法郎","691.88","人民币"],[100,"人民币","211.81","兰特"],[100,"人民币","16357.0","韩元"],[100,"人民币","52.667","迪拉姆"],[100,"人民币","53.787","里亚尔"],[100,"人民币","4112.74","福林"],[100,"人民币","55.012","兹罗提"],[100,"人民币","94.51","丹麦克朗"],[100,"人民币","131.33","瑞典克朗"],[100,"人民币","120.88","挪威克朗"],[100,"人民币","80.078","里拉"],[100,"人民币","291.41","比索"],[100,"人民币","474.61","泰铢"]]

如何将以上的JSON字符串转换成对应的二维数组对象并访问数组对象中的数据呢?

方案一

使用Json.NET组件的JsonConvert.DeserializeObject()方法,如下:

首先添加Newtonsoft.Json的命名空间引用:

using Newtonsoft.Json;

完整反序列化代码如下:

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

public class Program
{
    public static void Main()
    {
        var obj = JsonConvert.DeserializeObject<List<List<object>>>(JsonFile.Text);        
        Console.WriteLine("obj count:{0}",obj.Count);        
        foreach(var lst in obj)
        {
            Console.WriteLine("list count:{0}",lst.Count);
            lst.ForEach(x=>{
                Console.WriteLine("list item: {0}",x.ToString());
            });
        }
    }
}

public static class JsonFile
{
    public static string Text = "[[100,\"美元\",\"696.7\",\"人民币\"],[100,\"欧元\",\"789.23\",\"人民币\"],[100,\"日元\",\"6.1782\",\"人民币\"],[100,\"港元\",\"88.826\",\"人民币\"],[100,\"英镑\",\"891.04\",\"人民币\"],[100,\"人民币\",\"59.996\",\"林吉特\"],[100,\"人民币\",\"943.01\",\"卢布\"],[100,\"澳元\",\"493.89\",\"人民币\"],[100,\"加元\",\"529.98\",\"人民币\"],[100,\"新西兰元\",\"455.05\",\"人民币\"],[100,\"新加坡元\",\"503.4\",\"人民币\"],[100,\"瑞士法郎\",\"691.88\",\"人民币\"],[100,\"人民币\",\"211.81\",\"兰特\"],[100,\"人民币\",\"16357.0\",\"韩元\"],[100,\"人民币\",\"52.667\",\"迪拉姆\"],[100,\"人民币\",\"53.787\",\"里亚尔\"],[100,\"人民币\",\"4112.74\",\"福林\"],[100,\"人民币\",\"55.012\",\"兹罗提\"],[100,\"人民币\",\"94.51\",\"丹麦克朗\"],[100,\"人民币\",\"131.33\",\"瑞典克朗\"],[100,\"人民币\",\"120.88\",\"挪威克朗\"],[100,\"人民币\",\"80.078\",\"里拉\"],[100,\"人民币\",\"291.41\",\"比索\"],[100,\"人民币\",\"474.61\",\"泰铢\"]]";
}

运行结果部分输出如下:

obj count:24
list count:4
list item: 100
list item: 美元
list item: 696.7
list item: 人民币
list count:4
list item: 100
list item: 欧元
list item: 789.23
list item: 人民币
list count:4
list item: 100
list item: 日元
list item: 6.1782
list item: 人民币
...
...

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: [ASP.NET Core]ASP.NET Core应用程序开发中如何加密配置文件(appsettings.json)或者配置文件的选项?

下一篇: [ASP.NET Core Razor Pages系列教程]ASP.NET Core Razor Pages中的ASP.NET Core Razor 语法(08)

本文永久链接码友网 » [.NET/C#].NET/C#应用程序开发中如何将JSON字符串反序列化成二维数组对象?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册