I am trying to use an RESTFUL API for an application we use internally. One call to the API returns the following JSON:
{
"operation": {
"name": "GET RESOURCES",
"result": {
"status": "Success",
"message": "Query was successful"
},
"totalRows": 2,
"Details": [{
"RESOURCE DESCRIPTION": "Windows",
"RESOURCE TYPE": "Windows",
"RESOURCE ID": "101",
"RESOURCE NAME": "WINDOWSPC",
"NOOFACCOUNTS": "1"
}, {
"RESOURCE DESCRIPTION": "Ubuntu",
"RESOURCE TYPE": "Linux",
"RESOURCE ID": "808",
"RESOURCE NAME": "UBUNTUPC",
"NOOFACCOUNTS": "2"
}]
}
}
Using json.net I deseralize the json and check the stats with the following lines:
dynamic json = JsonConvert.DeserializeObject(response);
var status = json.operation.result.status.Value;
Next I want to get each value of each of the "Details" returned, but I cannot figure out how. I first tried getting the Details only with this:
var resourceList = json.operation.Details
Which works, but I cannot iterate over this to get just the "RESOURCE ID" and "RESOURCE NAME" for example.
I cannot use .Children() either, but when I hover over the resourceList there is a ChildrenTokens which seems to be what I want, but I cannot get at that in my code.
I also tried using resourceList as a DataSet as per their example but it throws an exception.
Can someone see what I am doing wrong..... I am not familiar with parsing JSON in C#
You can use Json.Linq for that and parse a response into JObject, then iterate it foreach loop. It's possible, since Details is an array and JObject implements IDictionary<string, JToken> and IEnumerable<KeyValuePair<string, JToken>>
var jObject = JObject.Parse(response);
foreach (var detail in jObject["operation"]["Details"])
{
var description = detail["RESOURCE DESCRIPTION"].Value<string>();
//other properties
}
Here's an example using the JObject class instead of dynamic
JObject json = JObject.Parse(response);
string status = json["operation"]["result"]["status"].Value<string>();
foreach (JToken resource in json["operation"]["Details"])
{
string id = resource["RESOURCE ID"].Value<string>();
string name = resource["RESOURCE NAME"].Value<string>();
}
It is as simple as this:
Your Model classes would look like:
public class Result
{
public string status { get; set; }
public string message { get; set; }
}
public class Detail
{
[JsonProperty("RESOURCE DESCRIPTION")]
public string ResourceDescription { get; set; }
[JsonProperty("RESOURCE TYPE")]
public string ResourceType { get; set; }
[JsonProperty("RESOURCE ID")]
public string ResourceId { get; set; }
[JsonProperty("RESOURCE NAME")]
public string ResourceName { get; set; }
[JsonProperty("NOOFACCOUNTS")]
public string NoOfAccounts { get; set; }
}
public class Operation
{
public string name { get; set; }
public Result result { get; set; }
public int totalRows { get; set; }
public List<Detail> Details { get; set; }
}
public class RootObject
{
public Operation operation { get; set; }
}
To de-serialize:
var json = JsonConvert.DeserializeObject<RootObject>(response);
To access a property:
var name=json.operation.name
To access your Details:
foreach(var item in json.operation.Details)
{
var myresourcename=item.ResourceName;
//So on
}
Related
I want to get data from json file correctly. The json data file I modeled for this is as follows:
{
"Free title 1":[
{
"Subject": "a1",
"Relation": "a2"
},
{
"Subject": "b1",
"Relation": "b2"
}
],
"Another free title":[
{
"Subject": "z1",
"Relation": "z2"
},
{
"Subject": "y1",
"Relation": "y2"
}
],
"Unordered title":[
{
"Subject": "x1",
"Relation": "x2"
},
{
"Subject": "w1",
"Relation": "w2"
}
]
}
This is how I create an object class:
public class _Infos_
{
public List<_Info_> Infos { get; set; }
}
public class _Info_
{
public string Subject { get; set; }
public string Relation { get; set; }
}
And finally I'm trying to get the data in a method like this:
var js = JsonConvert.DeserializeObject<_Infos_>(File.ReadAllText("__FILE_PATH__"));
foreach (var j in js.Infos)
{
MessageBox.Show(j.Subject);
}
I get the error that js is empty. Here I want to get Free title 1, Another free title and Unordered title in a list. Of course, these titles will be constantly changing. Afterwards, I want to get the Subject and Relation data under these titles. But I have no idea how to get it.
This data structure is a dictionary of collections of _Info_s. You need to deserialize it to Dictionary<string, List<_Info_>>.
Here are System.Text.Json and Json.net examples:
var d = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, List<_Info_>>>(json);
var d2 = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, List<_Info_>>>(json);
Your class definition is a little wrong.
You can use online tools "json to c#" to generate the correct classes.
like this one: https://json2csharp.com
Your "root" of your json for example does not contain an array in your json. The property "Free title 1":[..] is an array, so your root needs a property with the name FreeTitle1 and it has to be an array/list.
public class Root
{
[JsonProperty("Free title 1")]
public List<TitleInfo> FreeTitle1 { get; set; }
[JsonProperty("Another free title")]
public List<TitleInfo> AnotherFreeTitle { get; set; }
[JsonProperty("Unordered title")]
public List<TitleInfo> UnorderedTitle { get; set; }
}
public class TitleInfo
{
public string Subject { get; set; }
public string Relation { get; set; }
}
If your object members have dynamic names, you can also manually deserialize the object, e.g. using the general type JObject. E.g.
JObject obj = JObject.Parse(File.ReadAllText("__FILE_PATH__"));
JObject implements IEnumerable<KeyValuePair<string, JToken>> over which you can iterate.
Each member will then have JToken Value, which is a JArray in this case, which you can cast to a List of your type.
foreach (var groups in obj)
{
var infos = groups.Value.ToObject<List<_Info_>>();
// .. loop over infos
}
I have a json text and i want to get the values of author name and description tags. no need of other fields like url and urltoimage and all.
when i run the below code does not providing any string values. i think some error goes here.
{
"status": "ok",
"articles": [
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Khaled \"Tito\" Hamze",
"title": "Crunch Report",
"description": "Your daily roundup of the biggest TechCrunch stories and startup news.",
"url": "https://techcrunch.com/video/crunchreport/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2015/03/tccrshowogo.jpg?w=500&h=200&crop=1",
"publishedAt": "2017-12-11T20:20:09Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Sarah Perez",
"title": "Facebook is trying to make the Poke happen again",
"description": "Facebook's \"Poke\" feature has never really gone away, but now the social network is giving it a more prominent placement - and is even considering expanding..",
"url": "https://techcrunch.com/2017/12/11/facebook-is-trying-to-make-the-poke-happen-again/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/12/facebook-poke-icon.jpg",
"publishedAt": "2017-12-11T20:02:30Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Sarah Perez",
"title": "Amazon Alexa can now wake you up to music",
"description": "This fall, Amazon made a play to become your new alarm clock with the introduction of a combination smart speaker and clock called the Echo Spot. Today, the..",
"url": "https://techcrunch.com/2017/12/11/amazon-alexa-can-now-wake-you-up-to-music/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/09/amazon-event-9270069.jpg",
"publishedAt": "2017-12-11T17:22:30Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Ingrid Lunden, Katie Roof",
"title": "Apple confirms Shazam acquisition; Snap and Spotify also expressed interest",
"description": "After we broke the story last week that Apple was acquiring London-based music and image recognition service Shazam, Apple confirmed the news today. It is..",
"url": "https://techcrunch.com/2017/12/11/apple-shazam-deal/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/12/shazam-app-icon-ios.jpg",
"publishedAt": "2017-12-11T15:59:31Z"
}
]}
how to get this? below is my code and its not at all working
var data = (JObject)JsonConvert.DeserializeObject(myJSON);
string nameArticles= data["articles"].Value<string>();
MessageBox.Show(nameArticles);
public class Source
{
public string id { get; set; }
public string name { get; set; }
}
public class Article
{
public Source source { get; set; }
public string author { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public string urlToImage { get; set; }
public DateTime publishedAt { get; set; }
}
Article art = new Article();
art = JsonConvert.DeserializeObject<Article>(myJSON);
MessageBox.Show(art.description.ToString());
the above code return object not set to an instance error!
data["articles"] is likely to be a JArray not a string. You'll need to iterate over each JObject in the aforementioned JArray pulling out the author and description values
var data = (JObject)JsonConvert.DeserializeObject(myJSON);
var articles = data["articles"].Children();
foreach (var article in articles)
{
var author = article["author"].Value<string>();
var description = article["author"].Value<string>();
Console.WriteLine($"Author: " + author + ", Description: " + description);
}
This should help you get started with whatever you're doing.
If you do not want to create a wrapper class, you can try the below code snippet, which uses the dynamic type to deserialize JSON into an object.
var json = "Your JSON string";
dynamic stuff = JsonConvert.DeserializeObject(json);
string name = stuff.status;
var arr = stuff.articles;
foreach (var a in arr)
{
var authorName = a.author;
}
Assuming you wish to deserialize to concrete classes (as per the second attempted approach shown in your question) then you need a wrapper class to hold the whole object, and deserialise to that.
At the moment you're trying to serialise your entire object into an Article, but only the individual objects within the articles array of that object would match the structure in your Article class.
You're trying to do the action at the wrong level of your object, and also you're forgetting the fact that articles is a list (array).
Something like this:
public class JSONResponse
{
public string status { get; set; }
public List<Article> articles { get; set; }
}
and
JSONResponse response = JsonConvert.DeserializeObject<JSONResponse>(myJSON);
Then you can use a normal loop to iterate through the response.articles list and extract the author names and descriptions.
sample json data
string jsonString = "{\"displayName\":\"Alex Wu\",\"signInNames\":[{\"type\":\"emailAddress\",\"value\":\"AlexW#example.com\"},{\"type\":\"emailAddress\",\"value\":\"AlexW2#example.com\"}]}";
Convert json into jObject and get values using inbuilt method called selectToken()
JObject jObject = JObject.Parse(jsonString);
string displayName = (string)jObject.SelectToken("displayName");
string type = (string)jObject.SelectToken("signInNames[0].type");
string value = (string)jObject.SelectToken("signInNames[0].value");
Console.WriteLine("{0}, {1}, {2}", displayName, type, value);
JArray signInNames = (JArray)jObject.SelectToken("signInNames");
foreach (JToken signInName in signInNames)
{
type = (string)signInName.SelectToken("type");
value = (string)signInName.SelectToken("value");
Console.WriteLine("{0}, {1}", type, value);
}
Thank you
Your Json make below set of class
public class Source
{
public string id { get; set; }
public string name{get;set;}
}
public class Article
{
public Source source { get; set; }
public string author { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public string urlToImage { get; set; }
public DateTime publishedAt { get; set; }
}
public class RootObject
{
public string status { get; set; }
public List<Article> articles { get; set; }
}
So You Deserialize this by following way..
var data = JsonConvert.DeserializeObject<RootObject>(myJSON);
nameArticles=data.articles.FirstOrDefault().description;
MessageBox.Show(nameArticles);
Please create a class for your JSON file and add property for all tags
and then write code as below:
public class exampleJson{
public string author {get;set;}
public string description {get;set;}
.....
}
var data = JsonConvert.DeserializeObject<exampleJson>(myJSON);
string authorName = data.author;
string descriptions = data.description ;
I am coming to a problem where I am returning a whole guid from my rest api, however I just want to get the get the WelcomeMessage to show dynamically instead of hardcoding it. can anyone help me solve this issue. thanks for the help.
I have a child name Tests above the guid
Json:
{
"42f6be79-443b-4845-8549-865af9e74988": {
"Active": true,
"CompletedMessage": "Placeholder",
"CreatedBy": "",
"Description": "Placeholder",
"DisplayName": "Placeholder1",
"ID": "be193200-c277-48bd-90ab-796e869f2e0b",
"QuestionsIDs": [
"bd341962-6c7f-459d-88ea-86aa7186840a",
"bd341962-6c7f-459d-88ea-86aa7186840a"
],
"WelcomeMessage": "Placeholder3"
}
}
Code:
public Text welcomeMessage;
private async void welcomeMessage()
{
Dictionary<string, Questions> questionDictionary = new Dictionary<string, Questions>();
string json = #"{https://PROJECT_URL.firebaseio.com/Tests/WelcomeMessage.json";
questionDictionary = JsonConvert.DeserializeObject<Dictionary<string, Questions>>(json);
foreach (Questions question in questionDictionary.Values)
{
Guid[] guids = question.QuestionsIDs;
string welcomeMessage = question.WelcomeMessage;
welcomeMessageShown = GetComponent<Text>();
welcomeMessageShown.text = welcomeMessage.ToString();
}
First create a class that matches your object. Lets say Question
public partial class Question
{
[JsonProperty("Active")]
public bool Active { get; set; }
[JsonProperty("CompletedMessage")]
public string CompletedMessage { get; set; }
[JsonProperty("CreatedBy")]
public string CreatedBy { get; set; }
[JsonProperty("Description")]
public string Description { get; set; }
[JsonProperty("DisplayName")]
public string DisplayName { get; set; }
[JsonProperty("ID")]
public Guid Id { get; set; }
[JsonProperty("QuestionsIDs")]
public Guid[] QuestionsIDs { get; set; }
[JsonProperty("WelcomeMessage")]
public string WelcomeMessage { get; set; }
}
Since our json is a key value pair we need to deserialize it to a Dictionary
Our dictionary definition will be
Dictionary<string, Question> questionDictionary = new Dictionary<string, Question>();
Now using Newtonsoft.Json we can deserialize this to our dictionary.
string json = #"{
'42f6be79-443b-4845-8549-865af9e74988': {
'Active': true,
'CompletedMessage': 'Placeholder',
'CreatedBy': '',
'Description': 'Placeholder',
'DisplayName': 'Placeholder1',
'ID': 'be193200-c277-48bd-90ab-796e869f2e0b',
'QuestionsIDs': [
'bd341962-6c7f-459d-88ea-86aa7186840a',
'bd341962-6c7f-459d-88ea-86aa7186840a'
],
'WelcomeMessage': 'Placeholder3'
}
}";
Dictionary<string, Question> questionDictionary = JsonConvert.DeserializeObject<Dictionary<string, Question>>(json);
foreach (Question question in questionDictionary.Values)
{
Guid[] guids = question.QuestionsIDs; // Do whatever you want with it
string welcomeMessage = question.WelcomeMessage;
}
I have a json text and i want to get the values of author name and description tags. no need of other fields like url and urltoimage and all.
when i run the below code does not providing any string values. i think some error goes here.
{
"status": "ok",
"articles": [
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Khaled \"Tito\" Hamze",
"title": "Crunch Report",
"description": "Your daily roundup of the biggest TechCrunch stories and startup news.",
"url": "https://techcrunch.com/video/crunchreport/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2015/03/tccrshowogo.jpg?w=500&h=200&crop=1",
"publishedAt": "2017-12-11T20:20:09Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Sarah Perez",
"title": "Facebook is trying to make the Poke happen again",
"description": "Facebook's \"Poke\" feature has never really gone away, but now the social network is giving it a more prominent placement - and is even considering expanding..",
"url": "https://techcrunch.com/2017/12/11/facebook-is-trying-to-make-the-poke-happen-again/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/12/facebook-poke-icon.jpg",
"publishedAt": "2017-12-11T20:02:30Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Sarah Perez",
"title": "Amazon Alexa can now wake you up to music",
"description": "This fall, Amazon made a play to become your new alarm clock with the introduction of a combination smart speaker and clock called the Echo Spot. Today, the..",
"url": "https://techcrunch.com/2017/12/11/amazon-alexa-can-now-wake-you-up-to-music/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/09/amazon-event-9270069.jpg",
"publishedAt": "2017-12-11T17:22:30Z"
},
{
"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Ingrid Lunden, Katie Roof",
"title": "Apple confirms Shazam acquisition; Snap and Spotify also expressed interest",
"description": "After we broke the story last week that Apple was acquiring London-based music and image recognition service Shazam, Apple confirmed the news today. It is..",
"url": "https://techcrunch.com/2017/12/11/apple-shazam-deal/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/12/shazam-app-icon-ios.jpg",
"publishedAt": "2017-12-11T15:59:31Z"
}
]}
how to get this? below is my code and its not at all working
var data = (JObject)JsonConvert.DeserializeObject(myJSON);
string nameArticles= data["articles"].Value<string>();
MessageBox.Show(nameArticles);
public class Source
{
public string id { get; set; }
public string name { get; set; }
}
public class Article
{
public Source source { get; set; }
public string author { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public string urlToImage { get; set; }
public DateTime publishedAt { get; set; }
}
Article art = new Article();
art = JsonConvert.DeserializeObject<Article>(myJSON);
MessageBox.Show(art.description.ToString());
the above code return object not set to an instance error!
data["articles"] is likely to be a JArray not a string. You'll need to iterate over each JObject in the aforementioned JArray pulling out the author and description values
var data = (JObject)JsonConvert.DeserializeObject(myJSON);
var articles = data["articles"].Children();
foreach (var article in articles)
{
var author = article["author"].Value<string>();
var description = article["author"].Value<string>();
Console.WriteLine($"Author: " + author + ", Description: " + description);
}
This should help you get started with whatever you're doing.
If you do not want to create a wrapper class, you can try the below code snippet, which uses the dynamic type to deserialize JSON into an object.
var json = "Your JSON string";
dynamic stuff = JsonConvert.DeserializeObject(json);
string name = stuff.status;
var arr = stuff.articles;
foreach (var a in arr)
{
var authorName = a.author;
}
Assuming you wish to deserialize to concrete classes (as per the second attempted approach shown in your question) then you need a wrapper class to hold the whole object, and deserialise to that.
At the moment you're trying to serialise your entire object into an Article, but only the individual objects within the articles array of that object would match the structure in your Article class.
You're trying to do the action at the wrong level of your object, and also you're forgetting the fact that articles is a list (array).
Something like this:
public class JSONResponse
{
public string status { get; set; }
public List<Article> articles { get; set; }
}
and
JSONResponse response = JsonConvert.DeserializeObject<JSONResponse>(myJSON);
Then you can use a normal loop to iterate through the response.articles list and extract the author names and descriptions.
sample json data
string jsonString = "{\"displayName\":\"Alex Wu\",\"signInNames\":[{\"type\":\"emailAddress\",\"value\":\"AlexW#example.com\"},{\"type\":\"emailAddress\",\"value\":\"AlexW2#example.com\"}]}";
Convert json into jObject and get values using inbuilt method called selectToken()
JObject jObject = JObject.Parse(jsonString);
string displayName = (string)jObject.SelectToken("displayName");
string type = (string)jObject.SelectToken("signInNames[0].type");
string value = (string)jObject.SelectToken("signInNames[0].value");
Console.WriteLine("{0}, {1}, {2}", displayName, type, value);
JArray signInNames = (JArray)jObject.SelectToken("signInNames");
foreach (JToken signInName in signInNames)
{
type = (string)signInName.SelectToken("type");
value = (string)signInName.SelectToken("value");
Console.WriteLine("{0}, {1}", type, value);
}
Thank you
Your Json make below set of class
public class Source
{
public string id { get; set; }
public string name{get;set;}
}
public class Article
{
public Source source { get; set; }
public string author { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public string urlToImage { get; set; }
public DateTime publishedAt { get; set; }
}
public class RootObject
{
public string status { get; set; }
public List<Article> articles { get; set; }
}
So You Deserialize this by following way..
var data = JsonConvert.DeserializeObject<RootObject>(myJSON);
nameArticles=data.articles.FirstOrDefault().description;
MessageBox.Show(nameArticles);
Please create a class for your JSON file and add property for all tags
and then write code as below:
public class exampleJson{
public string author {get;set;}
public string description {get;set;}
.....
}
var data = JsonConvert.DeserializeObject<exampleJson>(myJSON);
string authorName = data.author;
string descriptions = data.description ;
I am getting the following error in Xamarin cross platform while deserializing the JSON Object. I have tried to do it with dictionary. But, everything gives me the same exception.
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[NBStudents.Models.jsonobjectclass+User]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.Path 'data.name', line 4, position 11.
My JSON Object Class:
public class jsonobjectclass
{
public class User
{
public string name { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string current_group { get; set; }
public List<UserGroups> user_groups { get; set; }
}
public class UserGroups
{
[JsonProperty("10")]
public string Student { get; set; }
[JsonProperty("15")]
public string Tutor { get; set; }
[JsonProperty("11")]
public string Parent { get; set; }
}
public class Token
{
public string access_token { get; set; }
public int expires_in { get; set; }
public string token_type { get; set; }
public string scope { get; set; }
public string refresh_token { get; set; }
public string error { get; set; }
}
public class UserResponse
{
public string msg { get; set; }
public List<User> data { get; set; }
public bool error { get; set; }
}
}
My Code to Deserialize JSON:
public static async Task<jsonobjectclass.UserResponse> UserRetrievalTask(string token, string apiUrl)
{
var jsonObject = new jsonobjectclass.UserResponse();
string readHttpResponse;
using (var httpClient = new HttpClient())
{
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, apiUrl))
{
httpRequestMessage.Headers.Add("Authorization", "Bearer " + token);
using (var httpResponse = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
{
readHttpResponse = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
var jObject = JObject.Parse(readHttpResponse);
try
{
jsonObject = JsonConvert.DeserializeObject<jsonobjectclass.UserResponse>(jObject.ToString());
}
catch(Exception ex)
{
string excep = ex.ToString();
readHttpResponse = excep;
}
}
}
}
return jsonObject;
}
My JSON String:
{{
"msg": null,
"data": {
"name": "geoit",
"email": "rokesh#geoit.in",
"phone": null,
"current_group": "11",
"user_groups": {
"11": "Parent"
}
},
"error": false
}}
Please Help me to solve this.
Thanks,
Rokesh
You have mismatch between the string and the object you are trying to deserialize into. The data object is not an array and there is an additional nested object which is not named in the JSON separately containing the msg field and the user data, but the error field is not part of that object:
As the comments have pointed out the JSON is not valid as is, so if you have control of the source I would fix that.
If not you could implement a reader and parse it as token by token, something like this:
using (var response = await client.GetAsync(_url, HttpCompletionOption.ResponseHeadersRead))
using (var stream = await response.Content.ReadAsStreamAsync())
using (var streamReader = new StreamReader(stream))
using (var reader = new JsonTextReader(streamReader))
{
var serializer = new JsonSerializer();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Start:
// code to handle it
break;
case JsonToken.PropertyName:
// code to handle it
break;
// more options
}
}
}
although this approach is more fragile. You can take a look at The JSON.Net JsonToken docs for more info.
Based on your comment and using https://jsonlint.com/ the response string
"{\"msg\":null,\"data\":{\"name\":\"geoit\",\"email\":\"rokesh#geoit.in\",\"phone\":null,\"current_group\":\"11\",\"user_groups\":{\"11\":\"Parent\"}},\"error\":false}"
is actually valid JSON, but the object is a little bizarre. I think it looks something like this in C#
public class UserGroup
{
public string 11 { get; set; }
}
public class UserData {
public string name { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string current_group { get; set; }
public UserGroup user_groups { get; set; }
}
public class ResponseObject
{
public string msg { get; set; }
public UserData data { get; set; }
public bool error { get; set; }
}
It should be an array the opening and closing brackets should be square brackets:
[
{ "msg": null,"data":
[ {
"name": "geoit",
"email": "rokesh#geoit.in",
"phone": null,
"current_group": "11",
"user_groups":
[{
"11": "Parent"
}
]
}
],
"error": false
}
]
Also in your code, you dont need var jObject = JObject.Parse(readHttpResponse); since the readHttpResponse is already a JSON string which you can deserialzie into an object.
Aplogies for the misleading answer earlier. The object you need to make array is the 'data' property of the response JSON. You have to get it from the server side as your Domainmodal List<User>. You should get a better understanding from this fiddle
readHttpResponse can be
{
"msg": null,
"data": [{
"name": "geoit",
"email": "rokesh#geoit.in",
"phone": null,
"current_group": "11",
"user_groups": {
"11": "Parent"
}
}],
"error": false
}
and
readHttpResponse.data needs to be array
[{
"name": "geoit",
"email": "rokesh#geoit.in",
"phone": null,
"current_group": "11",
"user_groups": {
"11": "Parent"
}
}]