.Net 读取Json文件中Object格式的数据

昨天在开发中有一项工作是将配置文件中Json格式的数据读取出来,并放到对应的数据对象中,网上有很多类似的例子,实现的方式也有很多,根据需求,我做了一个比较简单的例子,首先我们需要一个Json格式保存的配置文档。

config.json,保存样例如下:

{
    "Column1Width": 66,
    "SharedAreas": {
        "x": 70,
        "y": 70,
        "width": 1200,
        "height": 800
    },
    "SharedAreasPlus": {
        "x": 70,
        "y": 70,
        "width": 1300,
        "height": 800
    }
}

新建一个类,创建Json文件中的对象类,用于在代码中获取Json数据。

namespace WpfAppT
{
    public class AllSettings
    {
        public int Column1Width { get; set; }
        public SharedAreas SharedAreas { get; set; }
        public SharedAreasPlus SharedAreasPlus { get; set; }
    }
    public class SharedAreas
    {
        public int x { get; set; }
        public int y { get; set; }
        public int width { get; set; }
        public int height { get; set; }
    }
    public class SharedAreasPlus
    {
        public int x { get; set; }
        public int y { get; set; }
        public int width { get; set; }
        public int height { get; set; }
    }
}

接下来就是获取配置文件中的Json数据了,在这里我们使用了一个JsonMapper的依赖包。
导入依赖包的方法:选中项目的Dependencies,右击选中Manage Nuget Packages, 搜索"AWSSDK.Core"并安装。
在使用的时候通过using ThirdParty.Json.LitJson;进行使用。

下面是获取数据的方法:

static string path = string.Format("{0}config.json", AppContext.BaseDirectory);
public void getConfigCopyData()
{
   AllSettings allSettings = JsonMapper.ToObject<AllSettings>(File.ReadAllText(path));
   Console.WriteLine(allSettings);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值