This is my json :
"{\"sctoken\":\"a50395d5-571983f3-b394-4c6f-a26a-f95ae125fad6\",\"tms\":[{\"name\":\"ELTE MapCenterCache\",\"url\":\"http://cache2.smok.net.pl/cache_2015/element?s=%zoom%&x=%x%&y=%y%\"},{\"name\":\"OSM Mapnik\",\"url\":\"http://tile.openstreetmap.org/%zoom%/%x%/%y%.png\"},{\"name\":\"OSMElteMapa\",\"url\":\"http://osm.smok.net.pl/osm_tiles/%zoom%/%x%/%y%.png\"}],\"user_descr\":\"Pawel Okarmus\"}"
this how I convert json to class :
LoginResult loginResult = JsonConvert.DeserializeObject<LoginResult>(result.ToString());
class LoginResult
{
string sctoken { set; get; }
List<Maps> tms { set; get; }
}
class Maps
{
public string name { get; set; }
public string url { get; set; }
}
and my object LoginResult is empty
Try This
LoginResult loginResult = JsonConvert.DeserializeObject<RootObject>(result.ToString());
public class Tm
{
public string name { get; set; }
public string url { get; set; }
}
public class RootObject
{
public string sctoken { get; set; }
public List<Tm> tms { get; set; }
public string user_descr { get; set; }
}
It should work if you make the properties and the classes all public, so the deserializer can find & access them:
public class LoginResult
{
public string sctoken { set; get; }
public List<Maps> tms { set; get; }
}
public class Maps
{
public string name { get; set; }
public string url { get; set; }
}
You are also missing the element user_descr but that is not essential (you can still add it, or omit it if you don't need it).
You are missing Public in your LoginResult class , just put Public access modifier and it would start working (like this):
class LoginResult
{
public string sctoken { set; get; }
public List<Maps> tms { set; get; }
}
Related
I have the following Json returned from iTunes (I have replaced some details for privacy such as username and review content)
{"feed":{"author":{"name":{"label":"iTunes Store"}, "uri":{"label":"http://www.apple.com/uk/itunes/"}}, "entry":[
{"author":{"uri":{"label":"https://itunes.apple.com/gb/reviews/ID"}, "name":{"label":"Username"}, "label":""}, "im:version":{"label":"3.51"}, "im:rating":{"label":"4"}, "id":{"label":"12345"}, "title":{"label":"Review title"}, "content":{"label":"Review contents", "attributes":{"type":"text"}}, "link":{"attributes":{"rel":"related", "href":"https://itunes.apple.com/gb/review?reviewid"}}, "im:voteSum":{"label":"0"}, "im:contentType":{"attributes":{"term":"Application", "label":"Application"}}, "im:voteCount":{"label":"0"}},
// more entries ...
I want to deserialize this into a class. I only need the Review Title, Review contents, and the "im:rating" (which is the number of stars). However, I'm struggling due to the nested Json and the use of keys of how to extract this data. So far I have created a class ready to deserialize, and I have AppStoreData appStoreData = JsonConvert.DeserializeObject<AppStoreData>(stringResult); to deserialize it
public class AppStoreData {
}
My problem is that I don't know what to put inside the class to get the info I need from the Json. I have tried things such as:
public string title {get; set;}
public string content {get; set;}
public string imrating {get; set;}
However this doesn't work. I also think im:rating is an invalid name in C#.
Can anyone please help? Thank you
To get around the issue with im:rating you can use a JsonProperty attribute
[JsonProperty("im:rating")]
public Id ImRating { get; set; }
The issue with converting things like Label to string property is that it's not a string but an object in the input file.
You need something like
[JsonProperty("title")]
public Id Title { get; set; }
where Id is a class
public class Id
{
[JsonProperty("label")]
public string Label { get; set; }
}
Or write a deserializer that converts it to string for you.
I would suggest trying out one of many free code generators like https://app.quicktype.io/?l=csharp or http://json2csharp.com/ to get a headstart and edit everything to your liking afterwards.
I suggest using json2csharp to convert the json to c# model and change the invalid attributes by adding JsonProperty
public class Name
{
public string label { get; set; }
}
public class Uri
{
public string label { get; set; }
}
public class Author
{
public Name name { get; set; }
public Uri uri { get; set; }
}
public class Uri2
{
public string label { get; set; }
}
public class Name2
{
public string label { get; set; }
}
public class Author2
{
public Uri2 uri { get; set; }
public Name2 name { get; set; }
public string label { get; set; }
}
public class ImVersion
{
public string label { get; set; }
}
public class ImRating
{
public string label { get; set; }
}
public class Id
{
public string label { get; set; }
}
public class Title
{
public string label { get; set; }
}
public class Attributes
{
public string type { get; set; }
}
public class Content
{
public string label { get; set; }
public Attributes attributes { get; set; }
}
public class Attributes2
{
public string rel { get; set; }
public string href { get; set; }
}
public class Link
{
public Attributes2 attributes { get; set; }
}
public class ImVoteSum
{
public string label { get; set; }
}
public class Attributes3
{
public string term { get; set; }
public string label { get; set; }
}
public class ImContentType
{
public Attributes3 attributes { get; set; }
}
public class ImVoteCount
{
public string label { get; set; }
}
public class Entry
{
public Author2 author { get; set; }
[JsonProperty(PropertyName = "im:version")]
public ImVersion imversion { get; set; }
[JsonProperty(PropertyName = "im:rating")]
public ImRating imrating { get; set; }
public Id id { get; set; }
public Title title { get; set; }
public Content content { get; set; }
public Link link { get; set; }
[JsonProperty(PropertyName = "im:voteSum")]
public ImVoteSum imvoteSum { get; set; }
[JsonProperty(PropertyName = "im:contentType")]
public ImContentType imcontentType { get; set; }
[JsonProperty(PropertyName = "im:voteCount")]
public ImVoteCount imvoteCount { get; set; }
}
public class Feed
{
public Author author { get; set; }
public List<Entry> entry { get; set; }
}
public class RootObject5
{
public Feed feed { get; set; }
}
Once the model is ready you can use JsonConvert.DeserializeObject to convert the JSON to c# object
using (StreamReader r = new StreamReader(filepath)) {
string json = r.ReadToEnd();
var newEmps = JsonConvert.DeserializeObject<RootObject5>(json);
Console.WriteLine(newEmps.feed.entry[0].imvoteCount.label);
}
I am New to JSON and API
I am trying to get some data from an API for which I have Json and want to make a class for it.when I convert it using josn2csharp I get following code. Please let me know what sholud be the proper format of my class so that it converts into json.
public class DataSet {
public string __invalid_name__-i:nil { get; set; } }
public class GenericObject {
public string __invalid_name__-xmlns:d2p1 { get; set; }
public string __invalid_name__-i:type { get; set; }
public string __invalid_name__#text { get; set; } }
public class Message {
public string __invalid_name__-i:nil { get; set; } }
public class FunctionResponse {
public string __invalid_name__-xmlns:i { get; set; }
public string __invalid_name__-xmlns { get; set; }
public DataSet DataSet { get; set; }
public GenericObject GenericObject { get; set; }
public Message Message { get; set; }
public string Success { get; set; } }
public class RootObject {
public FunctionResponse FunctionResponse { get; set; } }
use this question as reference in this I came to know how to write for
public string invalid_name#text { get; set; }
but what about others.
please help
edit 1:
{
"DataSet": {
"#nil": "true"
},
"GenericObject": {
"#type": "d2p1:boolean",
"#text": "true"
},
"Message": {
"#nil": "true"
},
"Success": "true"
}
Example:
{
"json":
{
"#thekeyinsidejsonproperty": "value"
}
}
you shoud have
public class RootObject
{
[JsonProperty("json")]
public Json jsonobj;
}
public class Json
{
[JsonProperty("#thekeyinsidejsonproperty")]
public string somepropertyname{ get; set; }
}
hope it helps! :)
I have got following JSON that should be deserialized to C# class:
{"status":"error","messages":[{"level":"error","key":"InvalidTokenError","dsc":"Invalid
token"}]}
So I have a questions what is the kind of type should be
[{"level":"error","key":"InvalidTokenError","dsc":"Invalid token"}]
?
Is this array, list or class?
You can use json2csharp.com to get the types of the JSON.
JSON:
{"status":"error","messages":[{"level":"error","key":"InvalidTokenError","dsc":"Invalid token"}]}
Here is the classes generated for your JSON:
public class Message
{
public string level { get; set; }
public string key { get; set; }
public string dsc { get; set; }
}
public class RootObject
{
public string status { get; set; }
public List<Message> messages { get; set; }
}
for JSON:
[{"level":"error","key":"InvalidTokenError","dsc":"Invalid token"}]
Type:
public class Message
{
public string level { get; set; }
public string key { get; set; }
public string dsc { get; set; }
}
You can use this site
public class Message
{
public string level { get; set; }
public string key { get; set; }
public string dsc { get; set; }
}
public class RootObject
{
public string status { get; set; }
public List<Message> messages { get; set; }
}
I'm using the Petfinder API and trying to return a root object in my C# code. I used the Json class generator to generate the classes, but the Deserialize function is returning nulls.
This is my C# code:
using (var client = new WebClient())
{
var json = new WebClient().DownloadString("http://api.petfinder.com/shelter.getPets?format=json&key=<key>&id=<id>");
Petfinder deserializedPet = JsonConvert.DeserializeObject<Petfinder>(json);
}
The Petfinder object is defined as:
internal class Petfinder
{
[JsonProperty("#xmlns:xsi")]
public string XmlnsXsi { get; set; }
[JsonProperty("lastOffset")]
public LastOffset LastOffset { get; set; }
[JsonProperty("pets")]
public Pets Pets { get; set; }
[JsonProperty("header")]
public Header Header { get; set; }
[JsonProperty("#xsi:noNamespaceSchemaLocation")]
public string XsiNoNamespaceSchemaLocation { get; set; }
}
The first few lines of the json string is as follows:
{"#encoding":"iso-8859-1","#version":"1.0","petfinder":{"#xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","lastOffset":{"$t":"25"},"pets":{"pet":[{"options":{"option":[{"$t":"hasShots"},{"$t":"altered"},{"$t":"housetrained"}]},"breeds":{"breed":{"$t":"Domestic Medium Hair"}},"shelterPetId":{},"status":{"$t":"A"},"name":{"$t":"Jasmine"},...
If that helps at all.
I'm a newbie to json.net. What am I doing wrong?
Your class is wrong, take a look at the output from json2csharp.com for the example json you provided. Obviously the __invalid_name_$t needs to be manually fixed and the mapped using [JsonProperty].
public class LastOffset
{
public string __invalid_name__$t { get; set; }
}
public class Option
{
public string __invalid_name__$t { get; set; }
}
public class Options
{
public List<Option> option { get; set; }
}
public class Breed
{
public string __invalid_name__$t { get; set; }
}
public class Breeds
{
public Breed breed { get; set; }
}
public class ShelterPetId
{
}
public class Status
{
public string __invalid_name__$t { get; set; }
}
public class Name
{
public string __invalid_name__$t { get; set; }
}
public class Pet
{
public Options options { get; set; }
public Breeds breeds { get; set; }
public ShelterPetId shelterPetId { get; set; }
public Status status { get; set; }
public Name name { get; set; }
}
public class Pets
{
public List<Pet> pet { get; set; }
}
public class Petfinder
{
public string __invalid_name__#xmlns:xsi { get; set; }
public LastOffset lastOffset { get; set; }
public Pets pets { get; set; }
}
public class RootObject
{
public string __invalid_name__#encoding { get; set; }
public string __invalid_name__#version { get; set; }
public Petfinder petfinder { get; set; }
}
Am I missing something obvious here? JSON:
{"p":[{},{"clientId":102102059663,"checkbox1Ticked":false,"checkbox2Ticked":false},{"clientId":23841,"checkbox1Ticked":false,"checkbox2Ticked":false},{"clientId":102102111426,"checkbox1Ticked":false,"checkbox2Ticked":false}]}
C#: (checkboxData is the string above)
public JsonResult SubmitSelectedChanges(string checkboxData)
{
var deserializedClients = JsonConvert.DeserializeObject<ChangeList>(checkboxData);
return null;
}
public class ChangeList
{
public List<Change> p { get; set; }
}
public class Change
{
string clientId { get; set; }
bool checkbox1Ticked { get; set; }
bool checkbox2Ticked { get; set; }
}
After deserializing the clientId is always null and the checbox1Ticked and checkbox2Ticked is false.
It was because I had forgotten the access modifiers for the change class:
public class Change
{
public string clientId { get; set; }
public bool checkbox1Ticked { get; set; }
public bool checkbox2Ticked { get; set; }
}
I would have thought this would have thrown an exception.