Newtonsoft JSON deserialize and write data - json

I have the following class Visual Studio created from the JSON pasted below.
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string id { get; set; }
public string comments { get; set; }
public DateTime createdDate { get; set; }
public DateTime modifiedDate { get; set; }
public string createdBy { get; set; }
public string modifiedBy { get; set; }
}
-----JSON-----
[{"id":"00a17000000LmTOAA0","comments":"This is a comment or note added from code","createdDate":"2015-03-13T15:52:02.000+0000","modifiedDate":"2015-03-13T15:52:02.000+0000","createdBy":"Contact","modifiedBy":"Contact"},{"id":"00a17000000LmTTAA0","comments":"This is a comment or note added from code","createdDate":"2015-03-13T15:53:19.000+0000","modifiedDate":"2015-03-13T15:53:19.000+0000","createdBy":"Contact","modifiedBy":"Contact"},{"id":"00a17000000LmTYAA0","comments":"This is a comment or note added from code","createdDate":"2015-03-13T15:54:29.000+0000","modifiedDate":"2015-03-13T15:54:29.000+0000","createdBy":"Contact","modifiedBy":"Contact"},{"id":"00a17000000LmU7AAK","comments":"New Note Entered by Requester: This is a comment or note added from code","createdDate":"2015-03-13T16:39:43.000+0000","modifiedDate":"2015-03-13T16:39:43.000+0000","createdBy":"Contact","modifiedBy":"Contact"},{"id":"00a17000000LmW3AAK","comments":"added this comment from SalesF app as an agent","createdDate":"2015-03-13T17:37:24.000+0000","modifiedDate":"2015-03-13T17:37:24.000+0000","createdBy":"Agent","modifiedBy":"Agent"}]
I'm trying to create an object and do a foreach and get the data... I keep getting error Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {“name”:“value”}) to deserialize correctly.
I have tried this among other things:
var jsonResponseNotes = JsonConvert.DeserializeObject<Rootobject>(GetCommentsByID());
Any Ideas would be greatly appreciated!!!

you just need the root class:
public class RootObject
{
public string id { get; set; }
public string comments { get; set; }
public string createdDate { get; set; }
public string modifiedDate { get; set; }
public string createdBy { get; set; }
public string modifiedBy { get; set; }
}
and then deserialize it like this:
var result = JsonConvert.DeserializeObject<List<RootObject>>(json);

This is a list of your object. You will need to deserialize as such. Your code should be:
var jsonResponseNotes = JsonConvert.DeserializeObject<List<Class1>>(GetCommentsByID());
Edit
Just noticed your root object property is an array. Still, I believe arrays deserialize into list objects. I've adjusted my code.

Related

NewtonSoft.Json is returning null for all

I am using Microsoft.aspnetcore.mvc.newtonsoftjson(5.0.2) for JSON, I opted for this instead of System.Text.Json, because in latter one I could not find an option to ignore the loop.
When I try to de-serialize to an Object, it returns null for all properties...
[DataContract]
public class UserDefinition
{
public UserDefinition();
public string Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string EmailId { get; set; }
public string Token { get; set; }
public string RefreshToken { get; set; }
public List<string> AuthKey { get; set; }
public IList<SiteDefinition> AuthBranches { get; set; }
}
Data that needs to be Deserialize
Code used for deserialization...
ud = JsonConvert.DeserializeObject<UserDefinition>(erpResponse);
result
The reason is because of the attribute you've applied to your class:
[DataContract]
When this is present, Json.net will only consider properties that are attributed with [DataMember]. Since you didn't add this attribute to any of the properties, they're all ignored.
You have two solutions:
Remove [DataContract] from your class
Add [DataMember] to all relevant properties

C# JSON deserialization returns null

I'm trying to deserialize some statistics in JSON format from valve's API. The code below doesn't throw any exceptions when deserializing, only when trying to use the statistics afterwards. None of the statistics have a value after deserialization. Valve's response looks like this:
"playerstats":{
"steamID":"",
"gameName":"",
"stats":[
{
"name":"deaths",
"value":5062
}, etc etc..
This is my Rust class (Rust being the game I'm getting statistics from.):
public class Rust
{
public int steamID { get; set; }
public string gameName { get; set; }
public Array stats { get; set; }
}
And this is the deserialization code:
Rust getStats = JsonConvert.DeserializeObject<Rust>(str);
foreach (var stat in getStats.stats) //< ----- Exception: Object reference not set to an instance of an object.
{
parsed += stat.ToString();
}
'parsed' is then returned and used to print out all statistics and 'str' is the json response from Valve. I pasted the entire JSON response on pastebin in-case the above data isn't enough: https://pastebin.com/uJZSTF3G
I've tried naming some of the statistics individually in the Rust class instead of using an Array.
I expect the output to show all of the deserialized statistics for example in a console.
As #Bagus Tesa suggested, try something like...
public class Rust
{
public int steamID { get; set; }
public string gameName { get; set; }
public List<RustStat> stats { get; set; }
}
public class RustStat
{
public string name { get; set; }
public string value { get; set; }
}
Edit
I changed the steamID property to string and added the full code below. This compiled for me successfully. Hope this helps!
public class Valve
{
public Rust playerstats { get; set; }
}
public class Rust
{
public string steamID { get; set; }
public string gameName { get; set; }
public List<RustStat> stats { get; set; }
}
public class RustStat
{
public string name { get; set; }
public string value { get; set; }
}
Valve valve = JsonConvert.DeserializeObject<Valve>(str);
foreach (RustStat stat in valve.playerstats.stats)
{
}

Problems quering/deserializing multilevel field objects

https://opendata.miamidade.gov/Corrections/Jail-Bookings-May-29-2015-to-current/7nhc-4yqn?
I don't if someone could help me with this: I've been having problems parsing/de-serializing the Address information that comes inside the Location object.
This is a fragment of the code i am using:
var results = dataset.Query<MiamiDade_JailLog>(soql);
public class MiamiDade_JailLog
{
public string chargecode3 { get; set; }
public string charge2 { get; set; }
public string bookdate { get; set; }
public string charge3 { get; set; }
public string chargecode1 { get; set; }
public string chargecode2 { get; set; }
public string charge1 { get; set; }
public string dob { get; set; }
public Location1 location_1 { get; set; }
public string defendant { get; set; }
}
public class Location1
{
public bool needs_recoding { get; set; }
public string longitude { get; set; }
public string latitude { get; set; }
public HumanAddress human_address { get; set; }
}
public class HumanAddress
{
public string address { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
}
and this is the error message:
Error converting value
"{"address":"HOMELESS","city":"MIAMI","state":"FL","zip":""}" to type
'JailLog_WFA.HumanAddress'. Path 'location_1.human_address', line 1,
position 424.
This is the response I got from Socrata:
If you look at this json response, https://opendata.miamidade.gov/resource/7nhc-4yqn.json
You'll see that for the location_1 column, we provide an object, {}
and then within there you'll see human_address which we provide as a string "" instead of as an object.
For JavaScript, it would just be JSON.parse("{\"address\":\"17725 NW 8TH PL\",\"city\":\"MIAMI GARDENS\",\"state\":\"FL\",\"zip\":\"33169\"}");
From the code you sent, it looks like you are treating HumanAddress as an object instead of as a string that needs to be parsed into an object.
If you make this change it should work.
...And this was my response:
You gave me very good info. However I had already done a workaround to parse the object.
I just removed the extra quotes from the human_ address object and was able to parse everything at once.

Parsing JSON in C# 4.0

Can anyone help me to parse this JSON into an object IN C# 4.0. I have spent the last two days trying.
I have JSON.NET and several other peoples suggestions to no avail.
I thought it would be best just to give the JSON sample and to ask for your suggestions.
{
"message-count":"1",
"messages":[
{"to":"441234567890",
"messageprice":"0.02900000",
"status":"0",
"messageid":"030000001DFE2CB1",
"remainingbalance":"1.56500000",
"network":"23433"}
]
}
Many thanks,
Adrian
p.s Their is some nice code here, if you want to use github. https://github.com/lukesampson/HastyAPI.Nexmo
I will cheat and create C# classes quickly using this tool: http://json2csharp.com/ (or just discovered http://jsonclassgenerator.codeplex.com/)
Then I change C# classes to my liking
public class MessagesJSON
{
public int MessageCount { get; set; }
public List<Message> Messages { get; set; }
}
public class Message
{
public string To { get; set; }
public double MessagePrice { get; set; }
public int Status { get; set; }
public string MessageId { get; set; }
public double RemainingBalance { get; set; }
public string Network { get; set; }
}
MessagesJSON is just a name I made that represents the JSON object that you are passing to C#.
I pass the JSON string from the client, e.g.
{\"MessageCount\":1,\"Messages\":[{\"To\":\"441234567890\",\"MessagePrice\":0.029,\"Status\":0,\"MessageId\":\"030000001DFE2CB1\",\"RemainingBalance\":1.565,\"Network\":\"23433\"}]
Then I can use JSON.NET to convert JSON to C# objects:
public void YourMethod(MessagesJSON json) {
var result = JsonConvert.DeserializeObject<MessagesJSON>(json);
}
Here's the result:
Watch out for capitalisation.
If you want to use lower-case JSON keys only, change the C# classes to lower-case, e.g. public double messageprice { get; set; }
C# classes:
public class MessagesJSON
{
public int message_count { get; set; }
public List<Message> messages { get; set; }
}
public class Message
{
public string to { get; set; }
public string messageprice { get; set; }
public string status { get; set; }
public string messageid { get; set; }
public string remainingbalance { get; set; }
public string network { get; set; }
}
This is as close to your JSON as you want:
{\"message_count\":1,\"messages\":[{\"to\":\"441234567890\",\"messageprice\":\"0.02900000\",\"status\":\"0\",\"messageid\":\"030000001DFE2CB1\",\"remainingbalance\":\"1.56500000\",\"network\":\"23433\"}]}
or use one of these solutions if you really like CamelCasing:
CamelCase only if PropertyName not explicitly set in Json.Net?
JObject & CamelCase conversion with JSON.Net
I myself prefer attributes
public class Message
{
[JsonProperty("to")]
public string To { get; set; }
[JsonProperty("messageprice")]
public string MessagePrice { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("messageid")]
public string MessageId { get; set; }
[JsonProperty("remainingbalance")]
public string RemainingBalance { get; set; }
[JsonProperty("network")]
public string Network { get; set; }
}
Pass your string:
"{\"message_count\":1,\"messages\":[{\"to\":\"441234567890\",\"messageprice\":\"0.02900000\",\"status\":\"0\",\"messageid\":\"030000001DFE2CB1\",\"remainingbalance\":\"1.56500000\",\"network\":\"23433\"}]}"
but get the pretty C# property names:
Create objects with the same structure as the json and call.
JsonConvert.DeserializeObject<Entity>(json);
Edit. You have to use JSON.NET if u wanna do it this way.

ServiceStack: Deserializing a Collection of JSON objects

I have a simple json string which contains a collection of objects
http://sandapps.com/InAppAds/ads.json.txt
When I call GetAsync to get the objects, the collection returns 1 element instead of 4 and it's empty:
new JsonServiceClient ().GetAsync<List<CrossSell>> (url, Success, Failure);
My class is simple:
class CrossSell
{
public string ID { get; set; }
public string AppCategory { get; set; }
public string AppID { get; set; }
public string Name { get; set; }
public string ImageUrl { get; set; }
public string Copy { get; set; }
public string Device { get; set; }
public string Link { get; set; }
}
The JSON assumes a response DTO like:
class CrossSellResponse {
List<CrossSell> CrossSells { get; set; }
}
new JsonServiceClient().GetAsync<CrossSellResponse> (url, Success, Failure);
and not a bare array as your C# example suggests:
new JsonServiceClient ().GetAsync<List<CrossSell>> (url, Success, Failure);
I found the answer. You need to create an overall wrapper class that holds the JSON response. I call mine CrossSellResponse
public class CrossSellResponse
{
public List< CrossSell> CrossSells {get; set;}
}
The class CrossSell defines the data in the collection and matches the field names in a case sensitive way. The name of the response payload property CrossSells matches the name of the collection in the json stream.