0

i want to get the data from my returning api jsonstring.

my result string looks like this

 [
{"Id":12,"name":"testname","type":"testtype"}
{"Id":12,"name":"testname","type":"testtype"}
{"Id":12,"name":"testname","type":"testtype"}
 ]

how can i extract this data to c# objects

i can only do it ones

    var obj = JObject.Parse(result);
    var ID = (int)obj["Id"];
    var Name = (String)obj["name"];
    var type = (String)obj["type"];

 User u = new User(ID,Name,Type);
  • Your "result string" is not valid Json. At least not a valid object or collection, but rather three objects one after the other. I don't believe Json parsers will be able to handle this kind of response as it is. – madd0 Oct 20 '17 at 08:06
  • you **result** is an array of json – Rohit Kumar Oct 20 '17 at 08:22

2 Answers2

3

Your string is not valid JSON, so making it valid JSON is the first step to process it quickly. The easiest thing to do is to make it a JSON array:

string jsonArray = "["
                   + string.Join(", ", json.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                   + "]";

From then on it is straightforward (see my related answer: Easiest way to parse JSON response):

var result = JsonConvert.DeserializeObject<User[]>(jsonArray);

Another option is to split the lines yourself, and parse and add the items to a list manually.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

Result is an array of JSON.. so loop and parse

  list<User> userList = new list<User>();

    for(int i=0 ; i <result.length; i++)
    {
        var obj = JObject.Parse(result[i]);
        var ID = (int)obj["Id"];
        var Name = (String)obj["name"];
        var type = (String)obj["type"];

        User u = new User(ID,Name,Type); //create User

        userList.add(u);                 //Add to list
    }
Rohit Kumar
  • 1,777
  • 2
  • 13
  • 26