昨天在开发中有一项工作是将配置文件中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);
}