简体   繁体   中英

Converting JSON object to dynamic object

I need to get the values of my JSON object at the back end using C#. The JSON object is as follows:

{  "StudentName": "Michael Lumb",  "SubjectCodes": [    "1",    "2"  ],  "Grade": "3"}

The code I have tried is this:

public string AddStudent(JObject studentData)
{
 dynamic dObject = JObject.Parse(studentData.ToString());
 string _studentName = dObject.StudentName;//works fine
 string[] _subjectCodes= dObject.SubjectCodes;//gives error 'cannot implicitly convert type....'
}

My requirement is to get "SubjectCodes" as string array. How to achieve that?

Install newtonsoft:

Install-Package Newtonsoft.Json

Convert from json:

string json = "{ 'StudentName': 'Michael Lumb', 'SubjectCodes': ['1','2'], 'Grade': '3'}";
Student student = JsonConvert.DeserializeObject<Student>(json);

Convert to json:

string json = JsonConvert.Serialize(student);

http://james.newtonking.com/json下载NewtonSoft.dll,它具有将数据转换为json文件的方法,反之亦然

Found the answer in a similar StackOverflow question .

But you should also consider using strongly typed objects:

public class Student
{
    public string   StudentName  { get; set; }
    public string[] SubjectCodes { get; set; }
    public int      Grade        { get; set; }
}

...

var student = JsonConvert.DeserializeObject<Student>(json);
Console.WriteLine(student.SubjectCodes[0]);

C# is a strongly typed language and it's always preferable to describe your problem domain with strongly typed objects when possible. This way you gain the benefits of a strong type: compile time errors, refactoring, etc. If the json is incorrect, errors will be caught immediately when trying to deserialize, rather than potentially failing later down the line, where it's not immediately obvious what the problem is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM