I am giving up on this.
I've got the following Json that I need to deserialize:
json = "{
"2018-05-21": {
"lastUpdate": "2018-05-21 01:00:05",
"stops": [
{
"stopId": 1838,
"stopCode": "02"
}, {
"stopId": 1839,
"stopCode": "08"
}]}}";
var deserialized = JsonConvert.DeserializeObject<StopDate>(json); // null
and those classes:
public class StopDate
{
public BusStop date { get; set; }
}
public class BusStop
{
public string LastUpdate { get; set; }
public Stop[] Stops { get; set; }
}
public class Stop
{
public int StopId { get; set; }
public string StopName { get; set; }
}
The problem is that deserialized variable is null.
Apart from the overall ugliness when it comes to the names etc, I'd like it to be up and running just for a good start. All help's appreciated.
Convert the JSON to a Dictionary<DateTime, BusStop>
var deserialized = JsonConvert.DeserializeObject<Dictionary<DateTime, BusStop>>(json);
The DateTime key of the dictionary maps to the date in the JSON.
If the DateTime causes any issue then use a string as the key, ie Dictionary<string, BusStop> where the key can be parsed into a DateTime is needed
var deserialized = JsonConvert.DeserializeObject<Dictionary<string, BusStop>>(json);
BusStop busStop = deserialized["2018-05-21"];
And you probably want to make LastUpdate a DateTime rather than a string (as suggested by a commenter)
public class BusStop {
public DateTime LastUpdate { get; set; }
public Stop[] Stops { get; set; }
}
public class Stop {
public int StopId { get; set; }
[JsonProperty("stopCode")]
public string StopName { get; set; }
}
Related
using MessagePack;
[MessagePackObject]
public class CPegar_ids
{
[Key(0)]
public string operationName { get; set; }
[Key(1)]
public Variables variables { get; set; }
[Key(2)]
public string query { get; set; }
}
[MessagePackObject]
public class Variables
{
[Key(0)]
public object activeType { get; set; }
[Key(1)]
public string[] instruments { get; set; }
[Key(2)]
public string leverageInstrument { get; set; }
[Key(3)]
public int userGroupID { get; set; }
[Key(4)]
public string sortField { get; set; }
[Key(5)]
public string sortDirection { get; set; }
[Key(6)]
public int limit { get; set; }
[Key(7)]
public int offset { get; set; }
}
string json_data = #"
{
""operationName"": ""GetAssets"",
""variables"": {
""activeType"": null,
""instruments"": [
""BinaryOption"",
""DigitalOption"",
""FxOption"",
""TurboOption""
],
""leverageInstrument"": ""BinaryOption"",
""userGroupID"": 193,
""sortField"": ""Name"",
""sortDirection"": ""Ascending"",
""limit"": 20,
""offset"": 0
},
""query"": """"
}
";
var ob_ids = MessagePackSerializer.Deserialize<CPegar_ids>(Encoding.UTF8.GetBytes(json_data ));
Console.WriteLine($" IDS OB: {ob_ids.GetType()}");
https://github.com/neuecc/MessagePack-CSharp
I'm downloading JSON with HttpWebRequest, which returns a var string. I want to use this string to Deserialize with MessagePackSerializer. I've tried several different ways, with Utf8Json I can do it, but with this MessagePack I can't. I want to use MessagePack because it is much faster.
It looks like MessageBack have their own notation which is not JSON. But you're trying to deserialize Json into their custom notation which fails for obvious reasons. They seem to keep it small an compact by using more unicode in place of standard characters like JSON.
see https://msgpack.org/index.html
This is why you're not going to make it work putting in a JSON string and trying to deserialize it. If you're looking for faster JSON options there are a few other common alternatives to Newtonsoft Json.NET such as fastJSON https://github.com/mgholam/fastJSON
Reversing your sample code we can get an example of what the serialized values look like:
var myObject = new CPegar_ids {
operationName = "GetAssets",
variables = new Variables {
activeType = null,
instruments = new string[] {
"BinaryOption",
"DigitalOption",
"TurboOption"
},
leverageInstrument = "BinaryOption",
userGroupID = 193,
sortField = "Name",
sortDirection = "Ascending",
limit = 20,
offset = 0
},
query = ""
};
var bytes = MessagePackSerializer.Serialize(myObject);
Console.WriteLine(Encoding.UTF8.GetString(bytes));
the output of which is:
��operationName�GetAssets�variables��activeType��instruments��BinaryOption�DigitalOption�TurboOption�leverageInstrument�BinaryOption�userGroupID���sortField�Name�sortDirection�Ascending�limit14�offset00�query�
I couldn't find a good explanation on why it is not working. But there is a way to make it work instead of using Key(int index) attribute we will use Key(string propertyName) attribute.
Should you use an indexed (int) key or a string key? We recommend
using indexed keys for faster serialization and a more compact binary
representation than string keys. Reference.
OBJECTS
[MessagePackObject]
public class CPegar_ids
{
[Key("operationName")]
public string operationName { get; set; }
[Key("variables")]
public Variables variables { get; set; }
[Key("query")]
public string query { get; set; }
}
[MessagePackObject]
public class Variables
{
[Key("activeType")]
public object activeType { get; set; }
[Key("instruments")]
public string[] instruments { get; set; }
[Key("leverageInstrument")]
public string leverageInstrument { get; set; }
[Key("userGroupID")]
public int userGroupID { get; set; }
[Key("sortField")]
public string sortField { get; set; }
[Key("sortDirection")]
public string sortDirection { get; set; }
[Key("limit")]
public int limit { get; set; }
[Key("offset")]
public int offset { get; set; }
}
SERIALIZATION
var jsonByteArray = MessagePackSerializer.ConvertFromJson(File.ReadAllText("json1.json"));
CPegar_ids ob_ids = MessagePackSerializer.Deserialize<CPegar_ids>(jsonByteArray);
My project has a 3rd party web API that returns a json string in the following format (including the starting and ending curly braces):
{
"866968030210604":{
"dt_server":"2019-02-07 12:21:27",
"dt_tracker":"2019-02-07 12:21:27",
"lat":"28.844968",
"lng":"76.858502",
"altitude":"0",
"angle":"154",
"speed":"9",
"params":{
"pump":"0",
"track":"1",
"bats":"1",
"acc":"0",
"batl":"4"
},
"loc_valid":"1"
},
"866968030221205":{
"dt_server":"2019-02-07 12:20:24",
"dt_tracker":"2019-02-07 12:19:41",
"lat":"28.845904",
"lng":"77.096063",
"altitude":"0",
"angle":"0",
"speed":"0",
"params":{
"pump":"0",
"track":"1",
"bats":"1",
"acc":"0",
"batl":"4"
},
"loc_valid":"1"
},
"866968030212030":{
"dt_server":"0000-00-00 00:00:00",
"dt_tracker":"0000-00-00 00:00:00",
"lat":"0",
"lng":"0",
"altitude":"0",
"angle":"0",
"speed":"0",
"params":null,
"loc_valid":"0"
}
}
I want to deserialize it into a c# class object for further processing. I made the following class structure for the same:
class Params
{
public string pump { get; set; }
public string track { get; set; }
public string bats { get; set; }
public string acc { get; set; }
public string batl { get; set; }
}
class GPSData
{
public string dt_server { get; set; }
public string dt_tracker { get; set; }
public string lat { get; set; }
public string lng { get; set; }
public string altitude { get; set; }
public string angle { get; set; }
public string speed { get; set; }
public Params ObjParams { get; set; }
public string loc_valid { get; set; }
}
and I am trying the following code to deserialize:
JavaScriptSerializer jSerObj = new JavaScriptSerializer();
List<GPSData> lstGPSData = (List<GPSData>)jSerObj.Deserialize(json, typeof(List<GPSData>));
But every time it is showing NULL values assigned to each property of the class after the Deserialize() method is called. Please help me on this.
Your json is not in list format so deserializing to List<> isn't work
So you need to deserialize it into Dictionary<string, GPSData> like
JavaScriptSerializer jSerObj = new JavaScriptSerializer();
Dictionary<string, GPSData> lstGPSData = (Dictionary<string, GPSData>)jSerObj.Deserialize(json, typeof(Dictionary<string, GPSData>));
Usage:
foreach (var item in lstGPSData)
{
string key = item.Key;
GPSData gPSData = item.Value;
}
Also, you can list all your GPSData from above dictionary like,
List<GPSData> gPSDatas = lstGPSData.Values.ToList();
Output: (From Debugger)
Im having with the content. it is auto increment.
the result is static but the content is dynamic.
I'm using a hardcoded array in catching the return string from the web. Can anyone json decoder in converting the returned string to c# object
This is the returned string from web:
{
"result":{
"count":"3"
},
"content_1":{
"message_id":"23",
"originator":"09973206870",
"message":"Hello",
"timestamp":"2016-09-14 13:59:47"
},
"content_2":{
"message_id":"24",
"originator":"09973206870",
"message":"Test again.",
"timestamp":"2016-09-14 14:49:14"
},
"content_3":{
"message_id":"25",
"originator":"09973206870",
"message":"Another message",
"timestamp":"2016-09-14 14:49:20"
}
}
On site json2csharp.com you can generate classes for JSON data.
Generated classes needs some improvements and can look like:
public class Result
{
public string count { get; set; }
}
public class Content
{
public string message_id { get; set; }
public string originator { get; set; }
public string message { get; set; }
public string timestamp { get; set; }
}
public class RootObject
{
public Result result { get; set; }
public Content content_1 { get; set; }
public Content content_2 { get; set; }
public Content content_3 { get; set; }
}
And using JSON.NET you can deserialize it:
public class Program
{
static public void Main()
{
string json = "{ \"result\":{ \"count\":\"3\" }, \"content_1\":{ \"message_id\":\"23\", \"originator\":\"09973206870\", \"message\":\"Hello\", \"timestamp\":\"2016-09-14 13:59:47\" }, \"content_2\":{ \"message_id\":\"24\", \"originator\":\"09973206870\", \"message\":\"Test again.\", \"timestamp\":\"2016-09-14 14:49:14\" }, \"content_3\":{ \"message_id\":\"25\", \"originator\":\"09973206870\", \"message\":\"Another message\", \"timestamp\":\"2016-09-14 14:49:20\" } }";
RootObject ro = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(ro.content_1.message_id);
Console.WriteLine(ro.content_2.message_id);
}
}
I have a response from Jira API, require to be deserialized into data model:
com.atlassian.greenhopper.service.sprint.Sprint#40675167[id=10151,rapidViewId=171,state=CLOSED,name=Sprint 37.1,startDate=2015-07-30T16:00:22.000+03:00,endDate=2015-08-13T16:00:00.000+03:00,completeDate=2015-08-13T14:31:34.343+03:00,sequence=10151]
This is actually the information of current sprint for issue.
I need to deserialize it to a model like:
public class Model
{
public string name { get; set; }
...
}
I have already removed all non-required information, like com.atlassian.greenhopper.service.sprint.Sprint#40675167 using Regex pattern \[(.*?)\] so I have brackets and all inside.
Now I stopped completely trying to find the a way to convert this string to a data model.
Found the following thread at the Atlassian Answers page and there appears to be no JSON representation of that inner Object. As shown in the example from that thread:
customfield_10007:[
"com.atlassian.greenhopper.service.sprint.Sprint#a29f07[rapidViewId=<null>,state=CLOSED,name=NORD - Sprint 42,startDate=2013-07-29T06:47:00.000+02:00,endDate=2013-08-11T20:47:00.000+02:00,completeDate=2013-08-14T15:31:33.157+02:00,id=107]",
"com.atlassian.greenhopper.service.sprint.Sprint#769133[rapidViewId=<null>,state=ACTIVE,name=NORD - Sprint 43,startDate=2013-08-14T15:32:47.322+02:00,endDate=2013-08-23T15:32:47.322+02:00,completeDate=<null>,id=117]"
],
The response is indeed a JSON array, but the array itself contains CSV's, so you can make use of the following to parse that:
public class DataObject
{
public string id { get; set; }
public string rapidViewId { get; set; }
public string state { get; set; }
public string name { get; set; }
public string startDate { get; set; }
public string endDate { get; set; }
public string completeDate { get; set; }
public string sequence { get; set; }
}
public class Program
{
private const string sampleStringData =
#"[id=10151,rapidViewId=171,state=CLOSED,name=Sprint 37.1,startDate=2015-07-30T16:00:22.000+03:00,endDate=2015-08-13T16:00:00.000+03:00,completeDate=2015-08-13T14:31:34.343+03:00,sequence=10151]";
static void Main(string[] args)
{
var dataObject = new DataObject();
string[][] splitted;
var sampleWithNoBrackets = sampleStringData.Substring(1,sampleStringData.Length-2);
splitted = sampleWithNoBrackets.Split(',').Select(p => p.Split('=')).ToArray();
dataObject.id = splitted[0][1];
dataObject.rapidViewId = splitted[1][1];
dataObject.state = splitted[2][1];
dataObject.name = splitted[3][1];
dataObject.startDate = splitted[4][1];
dataObject.endDate = splitted[5][1];
dataObject.completeDate = splitted[6][1];
dataObject.sequence = splitted[7][1];
Console.ReadKey();
}
}
Here's the output for the above:
I have a JSON object that comes with a long list of area codes. Unfortunately each area code is the object name on a list in the Data object. How do I create a class that will allow RestSharp to deserialize the content?
Here's how my class looks now:
public class phaxioResponse
{
public string success { get; set; }
public string message { get; set; }
public List<areaCode> data { get; set; }
public class areaCode
{
public string city { get; set; }
public string state { get; set; }
}
}
And here's the JSON content:
{
success: true
message: "277 area codes available."
data: {
201: {
city: "Bayonne, Jersey City, Union City"
state: "New Jersey"
}
202: {
city: "Washington"
state: "District Of Columbia"
} [...]
}
Since this JSON is not C# friendly, I had to do a little bit of hackery to make it come out properly. However, the result is quite nice.
var json = JsonConvert.DeserializeObject<dynamic>(sampleJson);
var data = ((JObject)json.data).Children();
var stuff = data.Select(x => new { AreaCode = x.Path.Split('.')[1], City = x.First()["city"], State = x.Last()["state"] });
This code will generate an anonymous type that best represents the data. However, the anonymous type could be easily replaced by a ctor for a more normal DTO class.
The output looks something like this:
your json is incorrect, but if you do correct it you can use a json-to-csharp tool like the one on http://json2csharp.com/ to generate your classes:
public class __invalid_type__201
{
public string city { get; set; }
public string state { get; set; }
}
public class Data
{
public __invalid_type__201 __invalid_name__201 { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public string message { get; set; }
public Data data { get; set; }
}
I don't know anything about RestSharp, but if you're using Newtonsoft on the server side, then you can just pass a JObject to your method. Then you can interrogate the object to see what type of object it really is and use JObject.ToObject() to convert it.
I think using Dictionary<int,areaCode> is the easiest way.
public class phaxioResponse
{
public string success { get; set; }
public string message { get; set; }
public Dictionary<int,areaCode> data { get; set; }
public class areaCode
{
public string city { get; set; }
public string state { get; set; }
}
}
Then:
var res= JsonConvert.DeserializeObject<phaxioResponse>(json);
Console.WriteLine(string.Join(",", res.data));