I have a json response that looks like this:
"corps":
[
{
"id": "1007",
"company_id": "1007",
"org_name": "My organization 1",
"org_addr1": "123 W. 1234 S.",
"org_addr2": "",
},
{
"id": "1008",
"org_name": "My organization 2",
"org_addr1": "123 W. 1234 S.",
"org_addr2": "",
}
]
I have successfully gotten a single response into my HCO object properly using:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HCO));
HCO Company = (HCO)serializer.ReadObject(response.Content.ReadAsStreamAsync().Result);
This works well, but I'm trying to get all elements under corps. So I thought of trying something like this:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HCO));
HCO element = (HCO)serializer.ReadObject(response.Content.ReadAsStreamAsync().Result);
Companies.Add(element);
But this simply doesn't work. How do I parse the json result and then serialize each element in the response?
HCO Class:
public class HCO
{
public int id { get; set; }
public int comapny_id { get; set; }
public string org_name { get; set; }
public string org_addr1 { get; set; }
public string org_addr2 { get; set; }
}
You can wrap up the HCO class in a Response like this:
public class HCOResponse
{
public List<HCO> corps {get; set;}
}
And then try to deserialize the json using DataContractJsonSerializer like this:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HCOResponse));
Companies = (HCOResponse)serializer.ReadObject(response.Content.ReadAsStreamAsync().Result);
Hope it helps.
EDIT: (from feedback)
HCOResponse hco_resp = (HCOResponse)serializer.ReadObject(response.Content.ReadAsStreamAsync().Result);
Companies = hco_resp.corps;
Related
so I have a problem:
The code in JSON that you see there is a response that a webpage gives me. And the thing I want to do is really simple:
I just want to parse for example the "user_id", or "class".
I tried few things on stackoverflow that I found but no one works...
{
"data": {
"user": {
"class": "user",
"user_id": "81046537",
"etp_guid": "76411082-73ab-5aaa-9242-0bb752cf97a4",
},
},
}
Thanks !
There are many ways you can extract the user_id from the json. The most common way is to use Newtonsoft.Json package.
Assuming the json is stored as a string, you can call JObject.Parse().
var data = "{'data': {'user': {'class': 'user','user_id': '81046537','etp_guid': '76411082-73ab-5aaa-9242-0bb752cf97a4'} } }";
JObject jObject = JObject.Parse(data);
var userId = jObject["data"]["user"]["user_id"];
Console.WriteLine($"User id {userId}");
If your json is stored as a n object, then call JObject jObject = new JObject(data)
A preferred way is to serialise your json using business object. Simply create classes to match the json structure. e.g:
public class Response
{
public Data Data { get; set; }
}
public class Data
{
public User User { get; set; }
}
public class User
{
public string Class { get; set; }
public string User_id { get; set; }
public string Etp_guid { get; set; }
}
Then deserialize your object. e.g:
var response = JsonConvert.DeserializeObject<Response>(data);
Console.WriteLine($"User id {response.Data.User.User_id}");
I'm trying to deserialize a JSON response from WooCommerce with RestSharp.
I've been crawling this site for similar posts, but haven't found any solution.
My JSON (simplified)
[
{
"id":1,
"name":"product 1",
},
{
"id":2,
"name":"product 2",
}
]
Which translates into C# like this:
public class ProductResponse
{
public List<Product> products { get; set; }
}
public class Product
{
public int id { get; set; }
public string name { get; set; }
}
And is called like this
var response = client.Execute<ProductResponse>(request);
But it doesn't work, as the array of products doesn't have a name.
If the JSON is changed to
{
"products":
[
{
"id":1,
"name":"product 1",
},
{
"id":2,
"name":"product 2",
}
]
}
It works like a charm. Unfortunately I'm not able to change the JSON-format.
So how do I solve this?
Thanks in advance
You can annotate your product class to tell RestSharp which property is which:
public class Product
{
[DeserializeAs(Name = "id")]
public int id { get; set; }
[DeserializeAs(Name = "name")]
public string name { get; set; }
}
Then:
var response = client.Execute<List<Product>>(request);
You should now have a List<Product> with two correctly populated entries.
Original answer for posterity:
I don't have an answer for RestSharp (yet) but you could achieve this easily with Newtonsoft JSON if you can use that.
You can use the JsonProperty annotation like so:
public class Product
{
[JsonProperty("id")]
int id { get; set; }
[JsonProperty("name")]
string name { get; set; }
}
Then:
var products = JsonConvert.DeserializeObject<List<Product>>(json);
I think your deserialization actually should be List<Product> rather than ProductResponse.
E.g.
var response = client.Execute<List<Product>>(request);
Console.WriteLine("id = " + response[0].id) // id = 1
Console.WriteLine("name = " + response[0].name) // name = product 1
Console.WriteLine("id = " + response[1].id) // id = 2
Console.WriteLine("name = " + response[1].name) // name = product 2
So there is nothing wrong with the JSON string, I think the problem is you are expecting an object of type ProductResponse, where as your JSON string is an array/List of type Product.
SO I have a Json array as following:
{[data, [{"name":"Micheal Jackson","pic_large":"https://scontent.x.fbcdn.net/v/t1.0-1/p200x200/14909900_10154513795037597_3241587822245799922_n.jpg?oh=54ead7e0ba74b45b632d96da1515ccf8&oe=591C4938","id":"10154729171332597"}
How can I serialize it with C# to parse it into objects and then pass it to the view.
EDIT:
{[data, [{"name":"Sayed Zubair Hashimi","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/14909900_10154513795037597_3241587822245799922_n.jpg?oh=54ead7e0ba74b45b632d96da1515ccf8&oe=591C4938","id":"10154729171332597"},{"name":"Junaid Walizada","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/14055012_1760562554217155_4937121194048198140_n.jpg?oh=376b49c9d04c2676ebe3d853b122165e&oe=58EA033D","id":"1821833754756701"},{"name":"Mohib Akhondzada","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/s200x200/14264218_592094647641140_6351146344336469735_n.jpg?oh=a8a63893d71f76c45fa3d07389f1700a&oe=59147C84","id":"648198542030750"},{"name":"Za Beah","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15741112_359701871054520_6692094260041596196_n.jpg?oh=6d9a0e73f70145b821c79cbe738090a0&oe=58E5B5B5","id":"360411140983593"},{"name":"Baser Nader","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15094436_10153876544626432_1550234361821853528_n.jpg?oh=e197fa712b3180a20612ecdacb01747c&oe=58E54DEC","id":"10153975726331432"},{"name":"Abasin Deniz","pic_large":"https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15698075_440749809647293_7905213567074684088_n.jpg?oh=aeb22664f458d75fc00638ca6fa4ecfc&oe=591F7BB3","id":"444098429312431"}]]}
EDIT2:
Here is how I retrieve above Json.
var appsecret_proof = access_token.GenerateAppSecretProof();
var fb = new FacebookClient(access_token);
dynamic myFeed = await fb.GetTaskAsync(
("me/feed?fields=likes{{name,pic_large}}")
.GraphAPICall(appsecret_proof));
The strings shown in your question are all invalid JSON. A properly formatted JSON might look like this:
{
"data": [{
"name": "Micheal Jackson",
"pic_large": "https://scontent.x.fbcdn.net/v/t1.0-1/p200x200/14909900_10154513795037597_3241587822245799922_n.jpg?oh=54ead7e0ba74b45b632d96da1515ccf8&oe=591C4938",
"id": "10154729171332597"
}]
}
Now if you want to map this to C# class that's pretty easy to do. Just define the models to reflect this structure:
public class Feed
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("pic_large")]
public string PicLarge { get; set; }
}
public class Result
{
[JsonProperty("data")]
public IList<Feed> Feeds { get; set; }
}
and then all that's left is to deserialize the JSON string using a JSON serializer such as Json.NET back to this object structure:
string json = ... the json string shown above
var result = JsonConvert.DeserializeObject<Result>(json);
foreach (var feed in result.Feeds)
{
Console.WriteLine(feed.Name);
}
first you need to create class with properties same as in json and then use the following code :
class obj
{
public string name {get ; set; }
public string pic_large {get ; set; }
public id {get ; set; }
}
using System.Web.Script.Serialization;
.
.
var obj = new JavaScriptSerializer().Deserialize<obj>(jsonString);
I am pulling some JSON from an API. It comes in this format:
{"yourname": {
"id": 42728521,
"name": "Your Name",
"profileIconId": 27,
"revisionDate": 1397930999000,
"summonerLevel": 1
}}
However, that is stored as:
"{\"yourname\":{\"id\":42728521,\"name\":\"Your Name\",\"profileIconId\":27,\"summonerLevel\":1,\"revisionDate\":1397930999000}}"
Inside the string.
I want to be able to call summonerLevel and for it to return the correct value.
I've been trying this:
using (var client = new WebClient())
{
api_return = client.DownloadString(api_call_key);
}
var foo = JsonConvert.DeserializeObject<Summoner>(api_return);
Console.WriteLine(Summoner.id);
Console.WriteLine(Summoner.name);
Console.WriteLine(Summoner.summonerLevel);
string id_ = foo.ToString();
Console.WriteLine(id_);
Console.ReadKey();
}
public class Summoner
{
public static int id { get; set; }
public static string name { get; set; }
public static int summonerLevel { get; set; }
}
However, that just prints out:
0
nothing
0
You have two issues here, which are both preventing you from getting the data from the JSON.
The first issue is that the properties of your Summoner class should not be static, as Vikas pointed out. Define your class like this:
public class Summoner
{
public int id { get; set; }
public string name { get; set; }
public int summonerLevel { get; set; }
}
The second issue is that your JSON structure doesn't match what you're deserializing into. The id, name and summonerLevel properties are not at the root level of the JSON, they are one level further down, inside another object. So, you'll need to deserialize into some class that "wraps" your Summoner. If the yourname property in the JSON were a fixed value, you could define a Wrapper class like this to deserialize into:
public class Wrapper
{
[JsonProperty("yourname")]
public Summoner Summoner { get; set; }
}
However, since the yourname property in the JSON is likely not a fixed value (it could change for different summoners), I would recommend deserializing into a Dictionary<string, Summoner> like this instead:
var dict = JsonConvert.DeserializeObject<Dictionary<string, Summoner>>(json);
From there, you can either loop through the dictionary key-value pairs, or, if you're only expecting one, you can use First() to get it.
var summoner = dict.First().Value;
Here is a full demo:
string json = #"{""yourname"": {
""id"": 42728521,
""name"": ""Your Name"",
""profileIconId"": 27,
""revisionDate"": 1397930999000,
""summonerLevel"": 1
}}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, Summoner>>(json);
var summoner = dict.First().Value;
Console.WriteLine(summoner.id);
Console.WriteLine(summoner.name);
Console.WriteLine(summoner.summonerLevel);
Output:
42728521
Your Name
1
Properties in Summoner class should not be static
using (var client = new WebClient())
{
api_return = client.DownloadString(api_call_key);
}
var foo = JsonConvert.DeserializeObject<Summoner>(api_return);
Console.WriteLine(foo.id);
Console.WriteLine(foo.name);
Console.WriteLine(foo.summonerLevel);
..............
}
public class Summoner
{
public int id { get; set; }
public string name { get; set; }
public int summonerLevel { get; set; }
}
So I am trying to parse some JSON that is returned to me by a third party api that looks something like:
{
"status":"ok",
"links":
[
{
"link":
{
"link_name":"Sample",
"link_id":"9999"
}
},
],//and so on with other nested properties
I have created classes to map the JSON to
[DataContract]
public class JsonTestResults
{
[DataMember]
public string status { get; set; }
[DataMember]
public IEnumerable<Link> links { get; set; }
}
[DataContract]
public class Link
{
[DataMember]
public string link_name { get; set; }
[DataMember]
public string link_id { get; set; }
}
And I'm pushing the response through this deserializer (taken from this post
public T Deserialise<T>( string json )
{
T obj = Activator.CreateInstance<T>( );
using (MemoryStream ms = new MemoryStream( Encoding.Unicode.GetBytes( json ) ))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer( obj.GetType( ) );
obj = (T)serializer.ReadObject( ms );
return obj;
}
}
However, my deserialized results are showing the contents of Link[] as null. (there is a Link object for each one returned, but the link_name and link_id are null.)
I've checked out this, this, this, this and this, but haven't been able to solve this issue. I am looking for a solution that doesn't require a third party library. (per my lead dev).
I don't believe it's a problem with the classes matching the JSON, but I can post the full code if anyone would like to review it.
You need one more class to deserialize it correctly
public class JsonTestResults
{
public string status { get; set; }
public IEnumerable<TempLink> links { get; set; }
}
public class TempLink
{
public Link link;
}
public class Link
{
public string link_name { get; set; }
public string link_id { get; set; }
}
I tested it with Json.Net and worked.
var obj = JsonConvert.DeserializeObject <JsonTestResults>(json);
JavaScriptSerializer also works
var obj2 = new JavaScriptSerializer().Deserialize<JsonTestResults>(json);
Its a syntax error in the JSON,
In a JSON Array the last element does not have a ',' after it.
{
"status":"ok",
"links":
[
{
"link":
{
"link_name":"Sample",
"link_id":"9999"
}
}
],
This will work !!