I have a json like the example bellow and I'm using C# with json.net.
I'm trying to deserialize this json into a object, but it's not working.
{
"classes": [{
"id": 1,
"mask": 1,
"powerType": "rage",
"name": "Warrior"
}, {
"id": 2,
"mask": 2,
"powerType": "mana",
"name": "Paladin"
}, {
"id": 3,
"mask": 4,
"powerType": "focus",
"name": "Hunter"
}, {
"id": 4,
"mask": 8,
"powerType": "energy",
"name": "Rogue"
}, {
"id": 6,
"mask": 32,
"powerType": "runic-power",
"name": "Death Knight"
}, {
"id": 12,
"mask": 2048,
"powerType": "fury",
"name": "Demon Hunter"
}]
}
1) I created a class:
public class ClassJson
{
[JsonProperty(PropertyName = "classes")]
public Class Class { get; set; }
}
2) The second class:
public class Class
{
[JsonProperty(PropertyName = "id", NullValueHandling = NullValueHandling.Ignore)]
public int Id { get; set; }
[JsonProperty(PropertyName = "powerType", NullValueHandling = NullValueHandling.Ignore)]
public string PowerType { get; set; }
[JsonProperty(PropertyName = "name", NullValueHandling = NullValueHandling.Ignore)]
public string Name { get; set; }
}
I call the Api, get the json and I simply call JsonConvert.DeserializeObject<List<ClassJson>>(json). Nothing happens, no errors.
Can someone give me a tip in order to structure better the classes?
Try this instead because classes is supposed to be an array:
public class ClassJson
{
[JsonProperty(PropertyName = "classes")]
public Class[] classes { get; set; }
}
You do not need to write the classes to represent JSON manually. Refer my answer here on how to create a class representation of your JSON.
Related
Hi I try to get json data inside of the json. But my class is Employee my service creates json as com.myteam.rbffiyatlama2.Employee this prefix can be changeable so I have to write a solution to get an exact part of the json Like below but my below code is not working. I will send my node name to a method Getjsonobject(Employee emp) or Getjsonobject(Customer cust) or Getjsonobject(Student student) etc.
My Json:
{
"type": "SUCCESS",
"msg": "Container RBFFiyatlama2_1.0.1 successfully called.",
"result": {"execution-results": {
"results": [
{
"value": 2,
"key": ""
},
{
"value": {"com.myteam.rbffiyatlama2.Employee": {
"salary": 2400,
"age": 35,
"cofactor": 0.2
}},
"key": "t1"
},
{
"value": {"com.myteam.rbffiyatlama2.Employee": {
"salary": 4800,
"age": 35,
"cofactor": 0.2
}},
"key": "t2"
}
],
"facts": [
{
"value": {"org.drools.core.common.DefaultFactHandle": {"external-form": "0:50:1980606587:1980606587:100:DEFAULT:NON_TRAIT:com.myteam.rbffiyatlama2.Employee"}},
"key": "t1"
},
{
"value": {"org.drools.core.common.DefaultFactHandle": {"external-form": "0:51:2052360932:2052360932:99:DEFAULT:NON_TRAIT:com.myteam.rbffiyatlama2.Employee"}},
"key": "t2"
}
]
}}
}
class Program
{
static void Main(string[] args)
{
var employee1 = new Employee() { age = 35, cofactor = 0.2, salary = 2000 };
var employee2 = new Employee() { age = 35, cofactor = 0.2, salary = 4000 };
var list = new List<Employee>();
list.Add(employee1);
list.Add(employee2);
var uri = new Uri("http://localhost:8080/kie-server/services/rest/server/containers/instances/RBFFiyatlama2_1.0.1");
var kieclient = new KieRequestWrapper<Employee>(uri, "kieserver", "#test2018", MethodType.POST, "application/json").Add(list).Run();
Console.Write(kieclient.Content);
var match = Regex.Match(kieclient.Content, #"(?*.Employee{*})");
var result= MyParser.Parse(match, typeof(Employee)); //Desired
Console.Read();
}
}
public class Employee
{
public int age { get; set; }
public double cofactor { get; set; }
public int salary { get; set; }
}
You don't want to use XPath to get the data you need, you want to deserialize the the JSON string into an object and then get the data you need. There are many JSON serialization libraries out there, the most common one, AFAIK, is JSON.NET. You can look at how deserialization works here: https://www.newtonsoft.com/json/help/html/DeserializeObject.htm
Example:
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
string json = #"{
'Email': 'james#example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);
// james#example.com
Hello i've got this error Message
"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ClassLibraryMifosX.ViewModels.Rootobject2' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JS
my deserialize code :
Rootobject Rsc = JsonConvert.DeserializeObject<Rootobject>(json);
my class with json object description:
public class Rootobject
{
public List<Class1> Property1 { get; set; }
}
public class Class1
{
public int entityId { get; set; }
public string entityAccountNo { get; set; }
public string entityExternalId { get; set; }
public string entityName { get; set; }
public string entityType { get; set; }
public int parentId { get; set; }
public string parentName { get; set; }
public string entityMobileNo { get; set; }
public Entitystatus entityStatus { get; set; }
}
public class Entitystatus
{
public int id { get; set; }
public string code { get; set; }
public string value { get; set; }
}
my json :
[
{
"entityId": 1,
"entityAccountNo": "000000001",
"entityExternalId": "100001-241563",
"entityName": "Smith W R",
"entityType": "CLIENT",
"parentId": 1,
"parentName": "Head Office",
"entityMobileNo": "254728000000",
"entityStatus": {
"id": 300,
"code": "clientStatusType.active",
"value": "Active"
}
},
{
"entityId": 310,
"entityAccountNo": "000000310",
"entityName": "John Smith",
"entityType": "CLIENT",
"parentId": 14,
"parentName": "TestOffice1",
"entityStatus": {
"id": 300,
"code": "clientStatusType.active",
"value": "Active"
}
},
{
"entityId": 422,
"entityAccountNo": "000000422",
"entityExternalId": "smith1",
"entityName": "Smith Jones",
"entityType": "CLIENT",
"parentId": 11,
"parentName": "Barquisimeto",
"entityMobileNo": "88989898",
"entityStatus": {
"id": 300,
"code": "clientStatusType.active",
"value": "Active"
}
},
{
"entityId": 774,
"entityAccountNo": "000000774",
"entityName": "John AAA Smith",
"entityType": "CLIENT",
"parentId": 1,
"parentName": "Head Office",
"entityStatus": {
"id": 300,
"code": "clientStatusType.active",
"value": "Active"
}
},
{
"entityId": 1789,
"entityAccountNo": "Head Office000001789",
"entityExternalId": "547222",
"entityName": "Kaitlin Smith",
"entityType": "CLIENT",
"parentId": 1,
"parentName": "Head Office",
"entityStatus": {
"id": 300,
"code": "clientStatusType.active",
"value": "Active"
}
}
]
what i have been done wrongly ? Thanks
There is no root object into your Json data so just deserialize it as a collection of Class1 like below:
var collection = JsonConvert.DeserializeObject<List<Class1>>(json);
Don't forget that VS can create for you a class that can be used to deserailize your Json data. You don't need to write yourself the definition of Class1. Just go to menu => Edit > Paste Special > Paste JSON as classes
The first and last character of your JSON is a square bracket [ ] rather than a curly bracket { }. This means that it is an array, not an object. In order to parse it, you need to deserialize it into an array of Class1 objects:
Class1[] Rsc = JsonConvert.DeserializeObject<Class1[]>(json);
If you wanted to use a Rootobject object instead, you could then use it like so:
Rootobject root = new RootObject();
root.Property1 = new List<Class1>(Rsc);
I have a JSON array with nested objects, representing a menu, as this:
[
[
{
"name": "Item 1",
"id": 1
},
{
"name": "Item 2",
"id": 2,
"children": [
[
{
"name": "Item 21",
"id": 21
}
]
]
},
{
"name": "Item 3",
"id": 3,
"children": [
[
{
"name": "Item 31",
"id": 31,
"children": [
[
{
"name": "Item 311",
"id": 311
},
{
"name": "Item 312",
"id": 312
}
]
]
},
{
"name": "Item 32",
"id": 32
},
...
And I want to deserialize it using JavaScriptSerializer. I have some code as shown below but is not working.
var serializer = new JavaScriptSerializer();
var objects = serializer.Deserialize<Menu>(jsonData);
...
public class Menu
{
public int id { get; set; }
public string name { get; set; }
public Menu[] children { get; set; }
}
The error I get is "The type 'Menu' is not supported to deserialize a matrix".
I would appreciate any help on how to declare the custom object.
Cheers.
Your root object is a 2d jagged array of objects. The properties "children" are also 2d jagged arrays. Thus your Menu class needs to be:
public class Menu
{
public int id { get; set; }
public string name { get; set; }
public Menu [][] children { get; set; }
}
And deserialize your JSON as follows:
var serializer = new JavaScriptSerializer();
var objects = serializer.Deserialize<Menu [][]>(jsonData);
Alternatively, if you prefer lists to arrays, do:
public class Menu
{
public int id { get; set; }
public string name { get; set; }
public List<List<Menu>> children { get; set; }
}
And then
var objects = serializer.Deserialize<List<List<Menu>>>(jsonData);
Could the issue be that the actual data is an array but you're telling it to expect just one Menu?
It gives me error when deserializing this JSON File
{
"checkOut": "10:30",
"stars": 4,
"locationId": 953,
"propertyType": 6,
"checkIn": "15:00",
"trustyou": {
"languageSplit": [
{
"tripTypeSplit": [
{
"type": "family",
"percentage": 85
},
{
"type": "couple",
"percentage": 15
}
],
"name": "de",
"percentage": 100
}
],
"location": [
],
"reviewsCount": 83,
"popularity": 0,
"tripTypeSplit": [
{
"type": "family",
"percentage": 86
},
{
"type": "couple",
"percentage": 14
}
],
"sentimentScoreList": [
{
"categoryId": "14",
"ratio": "Good",
"shortText": "Great location",
"name": "Location",
"subcategories": [
],
"highlights": [
{
"text": "Beautiful location",
"confidence": 100
}
],
"reviewCount": 14,
"score": 100
},
{
"categoryId": "111",
"ratio": "Good",
"shortText": "Rather comfortable",
"name": "Comfort",
"subcategories": [
],
"highlights": [
],
"reviewCount": 5,
"score": 100
},
I have the following classes for this JSON
public class Root
{
[JsonProperty("checkIn")]
public string CheckIn { get; set; }
[JsonProperty("distance")]
public double Distance { get; set; }
[JsonProperty("hidden")]
public bool Hidden { get; set; }
[JsonProperty("trustyou")]
public Trustyou Trustyou { get; set; }
[JsonProperty("amenitiesV2")]
public AmenitiesV2 AmenitiesV2 { get; set; }
[JsonProperty("hasAirbnb")]
public bool HasAirbnb { get; set; }
[JsonProperty("checkOut")]
public string CheckOut { get; set; }
[JsonProperty("popularity")]
public int Popularity { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("cntRooms")]
public int CntRooms { get; set; }
What seems to be the problem? i'm deserializing this using
string resp2 = await client.GetStringAsync("");
var hotelDetails = JsonConvert.DeserializeObject<IDictionary<string, HotelsDescriptionAPI.Root>>(resp2, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
foreach (var hoteldesc in hotelDetails)
{
MessageBox.Show(hoteldesc.Value.Id);
}
and the exact error is
"Error converting value 24545 to type and Error converting value "10:30" to type 'HotelsDescriptionAPI.Root'. Path 'checkOut', line 1, position 19."
Im trying to get the value of "Id", What could be the problem with my code?
Your deserialization code should be:
var hotelDetails = JsonConvert.DeserializeObject<HotelsDescriptionAPI.Root>(resp2,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});
You're trying to deserialize it into a dictionary of string,Root, when the object itself is simply Root.
It does not seem to apply to your scenario, but note that when you do have JSON that is an array (root level children are array items, not properties), you may have to change the root object to subclass a compatible type.
For example:
public class RootObject : List<ChildObject>
{
}
public class ChildObject
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
For people that this does not help, and that are not using Entity Framework and or writing the domain classes by hand - make sure all your class properties match what is coming out of your data source in the same exact field order.
I'm calling the JIRA Rest API to recieve a list of Worklog Objects.
The JSON I recieve looks like.
{
"startAt": 0,
"maxResults": 1,
"total": 1,
"worklogs": [
{
"self": "http://www.example.com/jira/rest/api/2/issue/10010/worklog/10000",
"author": {
"self": "http://www.example.com/jira/rest/api/2/user?username=fred",
"name": "fred",
"displayName": "Fred F. User",
"active": false
},
"updateAuthor": {
"self": "http://www.example.com/jira/rest/api/2/user?username=fred",
"name": "fred",
"displayName": "Fred F. User",
"active": false
},
"comment": "I did some work here.",
"visibility": {
"type": "group",
"value": "jira-developers"
},
"started": "2015-08-25T07:43:10.086+0000",
"timeSpent": "3h 20m",
"timeSpentSeconds": 12000,
"id": "100028"
}
]
}
As I said, I want to put it in a list.
var json = client.MakeRequest("", password, user);
List<Worklog> myList = JsonConvert.DeserializeObject<List<Worklog>>(json);
It doesn't work, because of
"startAt": 0,
"maxResults": 1,
"total": 1,
How can I make the deserializer ignore those properties?
Thanks for your help!
Either create a "RootObject" class that does contain the properties:
public class RootObject
{
public int startAt { get; set; }
public int maxResults { get; set; }
public int total { get; set; }
public List<Worklog> worklogs { get; set; }
}
And deserialize into that:
var rootObject = JsonConvert.DeserializeObject<RootObject>(json);
// access rootObject.worklogs
Or step into the parsed JSON and deserialize from there:
JObject o = JObject.Parse(json);
JToken worklogsJson = o.SelectToken("worklogs");
var worklogs = worklogsJson.ToObject<List<Worklog>>();