ron ron - 1 month ago 14
C# Question

How to Convert JSON Object Array String to JSON Object Array to Custom Class in Xamarin

I am new in C# and Xamarin and want to convert json object array string to json object array to custom class in c#.

string test = @"{firstName: ""Sample First Name"", lastName: ""Sample Last Name""}";
Newtonsoft.Json.Linq.JObject sample = Newtonsoft.Json.Linq.JObject.Parse(test);
Console.WriteLine(sample);


The return will be like this which is correct:

{
"firstName": "Sample First Name",
"lastName": "Sample Last Name"
}


I think this is working since it is a single object but it is not working if my json object array string is like this which is I am getting from the response.

string test2 = @"[{firstName: ""Sample First Name"", lastName: ""Sample Last Name""},{firstName: ""Sample First Name 2"", lastName: ""Sample Last Name 2""}]";


How will i convert test2 to json object array?

Thanks in advance for your help.

Answer

In your example you didn't parse it into a custom class. You could do however:

public class Data
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

// ...
var test2 = @"[{firstName: ""Sample First Name"", lastName: ""Sample Last Name""},{firstName: ""Sample First Name 2"", lastName: ""Sample Last Name 2""}]";
var objects = JsonConvert.DeserializeObject<List<Data>>(test2);
Comments