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);
2
  • 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. Commented Oct 20, 2017 at 8:06
  • you result is an array of json Commented Oct 20, 2017 at 8:22

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

but how do you loop over the result? so i can put them in my object
Using a foreach over result.
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
    }

Comments