-3

I called REST API and was able to put the JSON response received back in a String using:

string vResp = new StreamReader(response.GetResponseStream(), Encoding.Default).ReadToEnd();

Below is the result of vResp from Console.WriteLine

{
  "Response" : [ {
    "UserID " : "23123213",
    "UserName " : "dms"
  }, {
    "UserID " : "542515",
    "UserName " : "ark"
  }, {
    "UserID " : "56546",
    "UserName " : "oneim"
  }, {
    "UserID " : "33336536",
    "UserName " : "cyberx"
  }, {
    "UserID " : "7563624",
    "UserName " : "bt"
  }, {
    "UserID " : "1221414",
    "UserName " : "azure"
  } ],
  "count" : "6"
}

I want to parse each UserID and UserName and insert each record in a table but not able to parse correctly. I tried different codes and I am able to separate Response and count but not able to reach one level below. Can anyone please help in this?

Jug B
  • 1
  • 1
  • https://www.newtonsoft.com/json – Robert Harvey Sep 05 '21 at 13:46
  • 1
    newtonsoft have a great tool called [json.net](https://www.newtonsoft.com/json) – styx Sep 05 '21 at 13:47
  • Remove `Encoding.Default`. It seems to work just by accident, since you only have base ASCII chars in the JSON. API usually return UTF8 encoded (the default encoding) data. – Jimi Sep 05 '21 at 14:24
  • Which version of .net are you using? – Andre.Santarosa Sep 05 '21 at 14:26
  • 2
    Please, provide us the REST calling implementation so we can have a big picture of how you are doing things. This allow us to provide a more accurate solution :) – Andre.Santarosa Sep 05 '21 at 14:28
  • HI, welcome to SO. Please [edit] and include your current solution. Also, please read [ask]. Also, if you are using .NET Core 3.x or .NET 5+, you can use the built-in `System.Text.Json` namespace for deserializing json strings. – Connor Low Sep 09 '21 at 16:16
  • Does this answer your question? [How can I parse JSON with C#?](https://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c) – Heretic Monkey Oct 28 '21 at 13:09
  • Does this answer your question? [Deserialize JSON with C#](https://stackoverflow.com/questions/7895105/deserialize-json-with-c-sharp) – ggorlen Oct 03 '22 at 23:34

1 Answers1

0

Create C# class that match with your vResp json result and then then use JSON.NET to deserialize the JSON data to created C# class objects.

You may refer this tool http://json2csharp.com/ to generate C# class based on your Json data.

Here is the code sample how you can parse Json data into C# class. User userObj = JsonConvert.DeserializeObject(vResp);

Now User will have parsing information and you can insert into table.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
  • Yes - I am doing the same but still having issue `var vJson = JsonConvert.DeserializeObject(vResp);` this is my code but when I do ` Console.WriteLine(vJson.Response.ToString());` I do not see the Response part of the JSON object. – Jug B Sep 05 '21 at 19:34