如何将json键映射到类属性

时间:2020-05-18 07:01:18

标签: c# json

我有一个json响应,如下所示

public class Robert {
 public string id { get; set; }
 public string class { get; set; }
 public string lastname { get; set; }

}
public class William {
 public string id { get; set; }
 public string class { get; set; }
 public string lastname { get; set; }

}
public class Application {
 public IList<Robert> Robert { get; set; }
 public IList<William> William { get; set; }

}

我想将其映射到c#类。 使用在线转换器,我得到以下结构

public class Student{
 public string Name{ get; set; } //Robert is mapped to this 
 public string id { get; set; }
 public string class { get; set; }
 public string lastname { get; set; }

}

相反,我想将学生姓名映射为班级属性之一,例如..“姓名”

COUNTIF

我该怎么做?

3 个答案:

答案 0 :(得分:1)

您可以像这样在JSON上阅读

var responseObject = JsonConvert.DeserializeObject<JObject>(responseStream); //Deserialized JSON to type of JObject
var robert = responseObject["Robert"].ToObject<Student>();

您的学生班级应该是这样

public class Student{ 
 public string id { get; set; }
 public string class { get; set; }
 public string lastname { get; set; }
}

以此,您可以读取Robert的ID,类,姓氏。

只是读取JSON响应之类的选项。

答案 1 :(得分:0)

Deserialize将json转换为Dictionary<string, List<Student>>,然后使用Linq转换为所需的对象

var strJSON = File.ReadAllText("json1.json");
var objStudents = JsonConvert.DeserializeObject<Dictionary<string, List<Student>>>(strJSON);
var result = objStudents.Select(x => new Student
{
    Name = x.Key,
    id = x.Value[0].id,
    studentclass = x.Value[0].studentclass,
    lastname = x.Value[0].lastname,
}).ToList();

答案 2 :(得分:0)

<!DOCTYPE html>
<html>
    <head>
        <meta charset = "UTF-8"/>
    </head>
    <body>
        <section>
            <input id="fileUpload" name="fileUpload" type="file"/>
            <button id="upload" type="button" onclick="uploadFile('test');">Go</button>
            <button id="download" type="button" onclick="downloadFile('test');">Download</button>
        </section>
    </body>
</html>
相关问题