多级嵌套json反序列化为实体对象c#
使⽤c#代码对json⽂件中的值进⾏修改,修改后再序列化为json⽂件
将多级嵌套的json⽂件,转化为类对象,反序列化
⽬录
1. 转化为类对象
json⽂件如下:
json⽂件放置在我本地⽂件夹:D:\2021\test.json
(1) 在vs中新建⼀个类
点击⾃⼰的project->右键-》Add-》New Item-》ProjectName.cs
(2) 打开要转化的json⽂件,全选复制,ctrl+A,ctrl+C
(3) 打开新建的类ProjectName.cs,点击vs⼯具栏编辑(Edit),到选择性粘贴(paste special) ,paste json as classes
(4) 粘贴完后发现已经⾃动转化
2. json⽂件反序列化
代码:
var jsonString = File.ReadAllText(@"D:\2021\test.json");
var rootobject = JsonConvert.DeserializeObject<Rootobject>(jsonString);
使⽤DeserializeObject()⽅法
可参考⽹站:
3. 获取并修改属性值
从ProjectName.cs中可以看出,获取属性值会⽐较复杂
因为本例中给的json⽂件中Rule[]为⼀个数组,所以使⽤了foreach遍历
private static string UpdateRules(string ruleName, bool isEnbaled, string ruleType, string bType, string[] prefixMatch, int createDays, int updateDays, int de        {
var jsonString = File.ReadAllText(@"D:\2021\test.json");
var rootobject = JsonConvert.DeserializeObject<Rootobject>(jsonString);
string id = rootobject.id;
string name = rootobject.name;
string type = pe;
Properties properties = rootobject.properties;
Policy policy = properties.policy;
Rule[] rules = policy.rules;
foreach (Rule rule in rules)
{
rule.name = ruleName;
Definition definition = rule.definition;json转换对象
Filters filters = definition.filters;
Actions actions = definition.actions;
filters.bTypes = bType;
filters.prefixMatch = prefixMatch;
Base _base = actions._base;
Create create = _ate;
Update update = _base.update;
Delete delete = _base.delete;
create.days = createDays;
update.days = updateDays;
delete.days = deleteDays;
}
string json = JsonConvert.SerializeObject(rootobject, Formatting.Indented);
Console.WriteLine(json);
return json;
}
4. 序列化
string json = JsonConvert.SerializeObject(rootobject, Formatting.Indented);
参考⽹站:
⾄此便完成了使⽤c#对json⽂件的修改。
该project完整代码见:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。