JSON JObject.Parse modifies json string - c#

I have got incomming Json in format:
{
"Type": "value",
"Name": "MeteoStation",
"UniqueAdress": "2C:3A:E8:0F:10:76",
"valuesList": [{
"Value": 23.00,
"Unit": "C",
"Type": "temperature",
"SourceUniqAdress": "2C:3A:E8:0F:10:76",
"TimeCaptured": "2018-03-26T09:36:13.200Z"
}]
}
In my program, I want to create object IValuePacket that is one value in list of values.
JObject jobject = JObject.Parse(incomingJson);
var settings = new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
var incommingMessage = JsonConvert.DeserializeObject<MessageEncapsulation>(incomingJson);
string Type = incommingMessage.Type;
string name = incommingMessage.Name;
if (string.IsNullOrWhiteSpace(name))
name = "no name";
if (Type.ToLower().Equals("value")) {
var values = JsonConvert.DeserializeObject<List<IValuePacket>>(jobject["valuesList"].ToString());
}
Everything works fine untill I recieved exact this json as mention above.
JObject.Parse modifies value TimeCaptured and jobject looks like:
{
"Type": "value",
"Name": "Meteostation",
"UniqueAdress": "2C:3A:E8:0F:10:76",
"valuesList": [{
"Value": 23.00,
"Unit": "C",
"Type": "temperature",
"SourceUniqAdress": "2C:3A:E8:0F:10:76",
"TimeCaptured": "2018-03-26T09:36:13.2Z"
}]}
Thats not so much difference, but DateTime.ParseExact(value, "yyyy-MM-ddThh:mm:ss.fffZ", System.Globalization.CultureInfo.InvariantCulture); cannot parse new value. Actually, I am sending 201 ms instead of 200 ms. It works, but I want to have good time for future reasons.
Is there any way how to avoid changing in Json during parsing?

It does not really modify your string, it just parses your date string into DateTime object when you call JObject.Parse. If you do this:
var obj = JObject.Parse(json);
var values = (JArray) obj["valuesList"];
var time = (JValue) values[0]["TimeCaptured"];
Console.WriteLine(time.Value.GetType());
You notice that time.Value is of type DateTime. Then you do this:
JsonConvert.DeserializeObject<List<IValuePacket>>(jobject["valuesList"].ToString());
By doing that you convert valueList back to json, but now TimeCaptured is DateTime and not a string, so that DateTime object is converted to json string using whatever date time format is used by JSON.NET by default.
You can avoid parsing strings that look like dates to .NET DateTime objects by parsing json to JObject like this:
JObject obj;
using (var reader = new JsonTextReader(new StringReader(json))) {
// DateParseHandling.None is what you need
reader.DateParseHandling = DateParseHandling.None;
obj = JObject.Load(reader);
}
Then type of TimeCaptured will be string, as you expect.
Side note: there is no need to convert JToken back to string and then call JsonConvert.Deserialize on that string. Instead, do this:
var values = obj["valuesList"].ToObject<List<IValuePacket>>();

Related

How do I parse this json string

I want to get the Cape URL but I'm having some trouble accessing It.
{
"timestamp": <java time in ms>,
"profileId": "<profile uuid>",
"profileName": "<player name>",
"signatureRequired": true, // Only present if ?unsigned=false is appended to url
"textures": {
"SKIN": {
"url": "<player skin URL>"
},
"CAPE": {
"url": "<player cape URL>"
}
}
}
I have tried multiple json methods but I can't figure out how to do it
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
dynamic dobj = jsonSerializer.Deserialize<dynamic>(thestring);
object result = dobj["textures"][0]["CAPE"][0]["url"];
It seem you are trying to treat the objects in your parsed json as some sort of array.
In both places where you've used [0], it is being done on an object. This would look for a key with the name 0 which doesn't exist.
Instead, you should just use the json keys directly.
Your final code should look something like this:
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
dynamic dobj = jsonSerializer.Deserialize<dynamic>(thestring);
object result = dobj["textures"]["CAPE"]["url"];

Sorting JObject inside array by a field value

I have a JSON string like below:
{
"MetaData": {
"ResourcesUsed": 1
},
"Result": [
{
"locations": [
{
"country": "Papua New Guinea",
"city": "Jacquinot Bay",
"locTypeAttributes": {
"localDate": "2018-10-08T04:21:00-07:00",
"utcDate": "2018-10-08T04:21:00-07:00",
},
"point": {
"coordinates": [
151.52,
-5.6
],
"type": "Point"
}
},{
"country": "Papua New Guinea2",
"city": "Jacquinot Bay2",
"locTypeAttributes": {
"localDate": "2018-10-08T04:21:00-07:00",
"utcDate": "2018-10-02T04:21:00-07:00",
},
"point": {
"coordinates": [
151.52,
-5.6
],
"type": "Point"
}
}
]
}
]
}
I converted it to a JSON object using Newtonsoft. What I want to do is to sort the locations array(s) inside the Result array by the utcDate field nested in each locations item. I found the following thread: C# Sort JSON string keys. However, I could not still implement it since I have arrays inside my object, while that question deals purely with sorting objects inside objects alphabetically by property name.
Here is a piece of code that I wrote so far:
public string GenerateJson()
{
var model = (JObject)JsonConvert.DeserializeObject(data);
Sort(model);
}
private void Sort(JObject jObj)
{
var props = jObj["Result"][0]["locations"].ToList();
foreach (var prop in props)
{
prop.Remove();
}
foreach (var prop in props.OrderBy(p => p.Name))
{
jObj.Add(prop);
if (prop.Value is JObject)
Sort((JObject)prop.Value);
if (prop.Value is JArray)
{
Int32 iCount = prop.Value.Count();
for (Int32 iIterator = 0; iIterator < iCount; iIterator++)
if (prop.Value[iIterator] is JObject)
Sort((JObject)prop.Value[iIterator]);
}
}
}
You can sort each individual "Result[*].locations" array using LINQ as follows:
// Load the JSON without parsing or converting any dates.
var model = JsonConvert.DeserializeObject<JObject>(data, new JsonSerializerSettings{ DateParseHandling = DateParseHandling.None });
// Construct a serializer that converts all DateTime values to UTC
var serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings{ DateTimeZoneHandling = DateTimeZoneHandling.Utc });
foreach (var locations in model.SelectTokens("Result[*].locations").OfType<JArray>())
{
// Then sort the locations by utcDate converting the value to UTC at this time.
var query = from location in locations
let utcDate = location.SelectToken("locTypeAttributes.utcDate").ToObject<DateTime>(serializer)
orderby utcDate
select location;
locations.ReplaceAll(query.ToList());
}
Notes:
The JSON is initially loaded using DateParseHandling.None to prevent the "localDate" and "utcDate" strings from being prematurely interpreted as DateTime objects with a uniform DateTime.Kind.
(For a discussion of how Json.NET interprets strings that look like dates, see Serializing Dates in JSON.)
We then iterate through all "locations" arrays using SelectTokens("Result[*].locations") where [*] is the JSONPath wildcard character, selecting all entries in the "Results" array.
We then order each "locations" array by deserializing the nested locTypeAttributes.utcDate to a UTC date, then ordering using LINQ.
Finally the array is updated using JArray.ReplaceAll().
If any locTypeAttributes.utcDate property is missing, an exception will be thrown. You could instead deserialize to DateTime? if that is a possibility.
Working sample .Net fiddle here.

Json.net incorrect parsing of date e.g. 2009-01-01T03:00:00.000Z

I'm having issues while parsing a Json object with Json.NET using DateTimeZoneHandling = DateTimeZoneHandling.Local in my JsonSerializerSettings.
The Json input is
{
'CreatedDate': '2009-01-01T03:00:00.000Z'
}"
and the value for de CreatedDate property is '2009-01-01T01:00:00-02:00'
If I try with another value, e.g. 1 year later, CreatedDate :'2010-01-01T03:00:00.000Z', the library works fine.
Here's my example, in a ConsoleApplication
string json = #"
{
'CreatedDate': '2009-01-01T03:00:00.000Z'
}";
var value = JsonConvert.DeserializeObject<object>(json, new JsonSerializerSettings()
{
DateTimeZoneHandling = DateTimeZoneHandling.Local
});
Console.Write(value);
Console.ReadKey();

How to get JSON values into a string array?

I am using VS2010 with C# 4. I have JSON similar to the following:
{"ItemDetails":{"Item":{"val": [
{"Description":"Desk1","Amount":"100.00"},
{"Description":"Desk2","Amount":"200.00"},
{"Description":"Desk3","Amount":"300.00"}]}}}
I want to get all the amount values into one string array like what is shown below:
amount={100.00,200.00,300.00}
How could I implement this? Do I have to loop through the JSON object or is there another way to do this?
I would recommend using NewtonSofts JSON library, but another (yet ugly) way is to use Regular Expressions.
var json = "{\"ItemDetails\":{\"Item\":{\"val\": [ " +
"{\"Description\":\"Desk1\",\"Amount\":\"100.00\",}," +
"{\"Description\":\"Desk2\",\"Amount\":\"200.00\",}," +
"{\"Description\":\"Desk3\",\"Amount\":\"300.00\"}}}";
// What I think you want
var amount = Regex.Matches(json, "Amount\":\"(.*?)\"").Cast<Match>().Select(m => m.Groups[1].Value).ToArray();
// Values 'converted' to json
var jsonAmount = "amount={" + string.Join(",", amount) + "}";
Using Json.Net you can do this with a LINQ-to-JSON query:
string json = #"
{
""ItemDetails"": {
""Item"": {
""val"": [
{
""Description"": ""Desk1"",
""Amount"": ""100.00""
},
{
""Description"": ""Desk2"",
""Amount"": ""200.00""
},
{
""Description"": ""Desk3"",
""Amount"": ""300.00""
}
]
}
}
}";
JToken token = JToken.Parse(json);
string[] amounts = token.SelectToken("ItemDetails.Item.val")
.Children()
.Select(t => t["Amount"].ToString())
.ToArray();
Console.WriteLine("amount={" + string.Join(",", amounts) + "}");
Output:
amount={100.00,200.00,300.00}
I am assuming you are not using JSON.NET. If this the case, then you can try it.
It has the following features -
LINQ to JSON
The JsonSerializer for quickly converting your .NET objects to JSON and back again
Json.NET can optionally produce well formatted, indented JSON for debugging or display
Attributes like JsonIgnore and JsonProperty can be added to a class to customize how a class is serialized
Ability to convert JSON to and from XML
Supports multiple platforms: .NET, Silverlight and the Compact Framework
Look at the example below.
In this example, JsonConvert object is used to convert an object to and from JSON. It has two static methods for this purpose. They are SerializeObject(Object obj) and DeserializeObject(String json) -
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject(json);

JSON trouble; deserialising to a datatable

I am trying to load JSON into a SQL database using JSON.net.
I've had no issues with other JSON responses however the following format doesn't seem to deserialise correctly.
{"Report":["2012m01d01","2012m01d02","2012w01","2012m01","2012m01d03","2012m01d04","2012m01d05","2012m01d06","2012m01d07","2012m01d08"],
"Realtime":null}
Could anybody provide some insight into why this would be? I'm using the following code to deserialise with.
public void Deserialize(String jsonText, ref DataTable dt)
{
JsonSerializer json = new JsonSerializer();
json.NullValueHandling = NullValueHandling.Ignore;
json.ObjectCreationHandling = ObjectCreationHandling.Replace;
json.MissingMemberHandling = MissingMemberHandling.Ignore;
json.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
StringReader sr = new StringReader(jsonText);
JsonTextReader reader = new JsonTextReader(sr);
dt = (DataTable)json.Deserialize(reader, typeof(DataTable));
reader.Close();
}
Any ideas on what the best approach to solving this would be? This works fine with other JSON responses!
Thanks in advance
JSON is able to hold hirarchial information, that does not translate into a single datatable, but rather into several using a dataset and table relationships.
I put your json in http://jsonlint.com validator and formatter
you say this deserializes with no problems
{
"accountID": 1,
"profileID": null,
"name": "Pages",
"ID": "18d039ae0360",
"language": n‌​ull,
"type": null,
"Category": null,
"IsHierarchy": false,
"IntervalsEnabled": true,
"IsRe‌​altimeCompatible": true,
"properties": null
}
this is a single object
but this doesn't deserialize properly.
{
"Report": [
"2012m01d01",
"2012m01d02",
"2012w01",
"2012m01",
"2012m01d03",
"2012m01d04",
"2012m01d05",
"2012m01d06",
"2012m01d07",
"2012m01d08"
],
"Realtime": null
}
Actually your problem is data handling not serializion
the first is a single object and can be deserialized into a DataTable
and the other is an object that holds a reference to a list of report objects.
therefore you need to manually write a converter from your object to two dataTables
this code works, and i'm sure you can create a conversion function for your two tables
var settings = new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Error,
NullValueHandling = NullValueHandling.Include
};
JsonSerializer json = JsonSerializer.Create(settings);
json.Error += (x, y) =>
{
var s = y.ErrorContext;
var t = y.CurrentObject;
};
StringReader sr = new StringReader(jsonString);
JsonTextReader reader = new JsonTextReader(sr);
var o = json.Deserialize<ClsReport>(reader);
string sf = o.ReportItems[2];
Hope this helps

Categories

Resources