【问题标题】:How to map JSON to an object with a different structure? [duplicate]如何将 JSON 映射到具有不同结构的对象? [复制]
【发布时间】:2017-04-11 03:34:50
【问题描述】:

我有一些带有此架构的 JSON:

{
    "person":{
        "name":"test",
        "family":"testi"
    },
    "Employee":{
        "id":54,
        "department":"web development",
        "skils":[{"type":"C#", "grade":"good"},{{"type":"SQL", "grade":"Expert"}}]
    }
}

我需要将此 JSON 映射到以下类:

class Employee {
    public int id { get; set; }
    public string Name { get; set; }
    public string Family { get; set; }
    public string Department { get; set; }
    public Skill[] Skills { get; set;}
}

class skill {
    public string Type { get; set; }
    public string Grade { get; set; }
}

现在有没有办法将我的 JSON 模式映射到我的 C# 对象? 我正在使用 Newtonsoft.Json 库并尝试像这样使用 JsonProperty 属性:

[JsonProperty("Person.Name")]

在我的Employee 课堂上。但这不起作用。有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: c# json json.net


    【解决方案1】:

    您的课程不适合您的 json。您必须均衡类的属性和 json 对象的属性。 你的 json 有一个名为 person 的属性,但你的类没有它。

    MappedObject mappedObject = JsonConvert.DeserializeObject<MappedObject>(yourJson);
    
    class MappedObject{
        public Person person;
        public Employee employee; 
    }
    
    class Person{
        public string name;
        public string family;
    }
    class Employee {
        public intid{get; set;}
        public string deartment {get; set;}
        public Skill[] skills {get; set;}
    }
    class skill{
        public string type{get; set;}
        public string grade{get; set;}
    }
    

    或者更好的方式你可以使用动态对象。

    dynamic result = new ExpandoObject();
    result = JsonConvert.DeserializeObject(yourJson);
    

    【讨论】:

    • 我这样做......它工作得很好......我的项目是其他服务的包装器,我必须使用我自己的模式发送对象......我可以使用自动映射器但是这个导致创建一个额外的步骤来将 MappedObject 转换为我的架构。我想减少这一步
    • 所以你应该使用我的第一个代码。
    • 但它没有填写员工姓名和家庭财产......
    • 所以你可以发送或使用 mappedObject.employee 但你必须从你的 json 中填充它们。填充后不要使用它们。
    • Employee 类中存在错误。它仍然包含 NameFamily 属性——它们不是初始 json 模式的一部分。并且 - 为了成功映射 - 属性名称的大写应该是一致的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多