Cannot convert json to object - c#

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);

Related

Add item to JSON array section in C#

{
"name": "Not Okay Bears Solana #1",
"image": "ipfs://QmV7QPwmfc6iFXw2anb9oPZbkFR75zrtw6exd8LherHgvU/1.png",
"attributes": [
{
"trait_type": "Background",
"value": "Amethyst"
},
{
"trait_type": "Fur",
"value": "Warm Ivory"
},
{
"trait_type": "Mouth",
"value": "Clean Smile"
},
{
"trait_type": "Eyes",
"value": "Not Okay"
},
{
"trait_type": "Hat",
"value": "Bucket Hat"
},
{
"trait_type": "Clothes",
"value": "Plaid Jacket"
},
{
"trait_type": "Eyewear",
"value": "Plastic Glasses"
}
],
"description": "Not Okay Bears Solana is an NFT project for mental health awareness. 10k collection on the Polygon blockchain. We are not okay."
}
I need to add an object to attributes.
How to do this?
My JSON classes:
public class Attribute
{
public string trait_type { get; set; }
public string value { get; set; }
}
public class Root
{
public string name { get; set; }
public string image { get; set; }
public List<Attribute> attributes { get; set; }
public string description { get; set; }
}
try this, in this case you don't need any classes
var jsonObject = JObject.Parse(json);
JObject obj = new JObject();
obj.Add("trait_type", "type");
obj.Add("value", "value");
((JArray)jsonObject["attributes"]).Add(obj);
var newJson=jsonObject.ToString();
but if you need the data not a json , you can use this code
Root data = JsonConvert.DeserializeObject<Root>(json);
data.attributes.Add(new Attribute { trait_type="type", value="value"});

C#, Deserialize json

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.

Deserialize nested JSON array in C#

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?

JSON Error converting value to type

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.

Deserialize JSON subdocument

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>>();

Categories

Resources