I need to rearrange a JSON but I cant find a solution - c#

This is the JSON im receiving, already filtered. (its coming from the google places autocomplete API)
{
"predictions": [
{
"description": "Frankfurt am Main, Deutschland",
"place_id": "ChIJxZZwR28JvUcRAMawKVBDIgQ",
},
{
"description": "Frankfurt (Oder), Deutschland",
"place_id": "ChIJb_u1AiqYB0cRwDteW0YgIQQ",
},
{
"description": "Frankfurt Hahn Flughafen (HHN), Lautzenhausen, Deutschland",
"place_id": "ChIJX3W0JgQYvkcRWBxGlm6csj0",
}
],
"status": "OK"
}
And I need to get this JSON into this format:
{
"success":true,
"message":"OK",
"data":[
{
"description":"Frankfurt Hahn Flughafen (HHN), Lautzenhausen, Deutschland",
"id":"ChIJX3W0JgQYvkcRWBxGlm6csj0"
},
{
"description":"Frankfurt Airport (FRA), Frankfurt am Main, Deutschland",
"id":"ChIJeflCVHQLvUcRMfP4IU3YdIo"
},
{
"description":"Frankfurt Marriott Hotel, Hamburger Allee, Frankfurt am Main, Deutschland",
"id":"ChIJdag3xFsJvUcRZtfKqZkzBAM"
}
]
}
I would be very g
So predictions is just renamed to "data", we change rename status to message, move it up and add a success if the http-request that happened earlier was a success or not. This does not seem so hard on the first catch, but I can't seem to find resources to transform or rearrange JSON in C#.
I would be very grateful for any tips or resources, so I can get unstuck on this probably not so difficult task. I should mention I'm fairly new to all of this.
Thank you all in advance!

First create classes thats represent your jsons
public class Prediction
{
public string description { get; set; }
public string place_id { get; set; }
}
public class InputJsonObj
{
public Prediction[] predictions { get; set; }
public string status { get; set; }
}
public class Datum
{
public string description { get; set; }
public string id { get; set; }
}
public class OutPutJsoObj
{
public bool success { get; set; }
public string message { get; set; }
public List<Datum> data { get; set; }
public OutPutJsoObj(){
data = new List<Datum>();
}
}
Then mapped objects (manually or using any of mapping libraries like AutoMapper) and create final json.
using Newtonsoft.Json;
InputJsonObj inputObj = JsonConvert.DeserializeObject<InputJsonObj >(inputJson);
OutPutJsoObj outObj = new OutPutJsoObj ();
foreach(var p in inputObj)
{
outObj.Data.Add(new Datum() { descriptions = p.descriptions , id= p.place_id }
}
string outJson = = JsonConvert.SerializeObject(outObj);

Just parse the origional json and move the data to the new json object
var origJsonObj = JObject.Parse(json);
var fixedJsonObj = new JObject {
new JProperty("success",true),
new JProperty("message",origJsonObj["status"]),
new JProperty("data",origJsonObj["predictions"])
};
it is not clear from your question what should be a success value, but I guess maybe you need this line too
if (fixedJsonObj["message"].ToString() != "OK") fixedJsonObj["success"] = false;
if you just need a fixed json
json = fixedJsonObj.ToString();
or you can create c# class (Data for example) and deserilize
Data result= fixedJsonObj.ToObject<Data>();

I like the answer from #Serge but if you're looking for a strongly typed approach we can model the input and output structure as the same set of classes and the output structure is similar, with the same relationships but only different or additional names this try this:
The process used here is described in this post but effectively we create write-only properties that will receive the data during the deserialization process and will format it into the properties that are expected in the output.
public class ResponseWrapper
{
[JsonProperty("success")]
public bool Success { get;set; }
[JsonProperty("message")]
public string Message { get;set; }
[Obsolete("This field should not be used anymore, please use Message instead")]
public string Status
{
get { return null; }
set
{
Message = value;
Success = value.Equals("OK", StringComparison.OrdinalIgnoreCase);
}
}
[JsonProperty("data")]
public Prediction[] Data { get;set; }
[Obsolete("This field should not be used anymore, please use Data instead")]
public Prediction[] Predictions
{
get { return null; }
set { Data = value; }
}
}
public class Prediction
{
public string description { get; set; }
public string place_id { get; set; }
}
Then you can deserialize and re-serialize with this code:
using Newtonsoft.Json;
...
var input = JsonConvert.DeserializeObject<ResponseWrapper>(input);
var output = JsonConvert.SerializeObject(objs, new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
});
This is a fiddle you can test with: https://dotnetfiddle.net/DsI5Yc
And the output:
{
"success": true,
"message": "OK",
"data": [
{
"description": "Frankfurt am Main, Deutschland",
"place_id": "ChIJxZZwR28JvUcRAMawKVBDIgQ"
},
{
"description": "Frankfurt (Oder), Deutschland",
"place_id": "ChIJb_u1AiqYB0cRwDteW0YgIQQ"
},
{
"description": "Frankfurt Hahn Flughafen (HHN), Lautzenhausen, Deutschland",
"place_id": "ChIJX3W0JgQYvkcRWBxGlm6csj0"
}
]
}
If you were going to go to the trouble of writing a converter for the deserialization then I find this solution is a bit simpler. I tend to use this type of solution when exposing additional properties to allow legacy data to map into a the current code base.
keeps the mapping and logic contained within the class
tells developers still writing code against the deprecated structures about the change
You can also augment this and implement a global converter to omit obsolete properties which would give you full backwards compatibility until you update the source to stop sending the legacy structure. This is a fiddle of such a solution: https://dotnetfiddle.net/MYXtGT
Inspired by these posts:
JSON.Net Ignore Property during deserialization
Is there a way to make JavaScriptSerializer ignore properties of a certain generic type?
Exclude property from serialization via custom attribute (json.net)
Json.NET: Conditional Property Serialization

Related

Deserialize complex JSON object fails to see collection

I've simplified the code (below) but I cannot figure out why the Result.Data property is not getting filled; it is always null. I've used jsonlint.com to validate the JSON (both this small sample and the full content). I built a separate project (using How to Deserialize a Complex JSON Object in C# .NET) and it successfully serializes the complex object listed there. But I cannot get this one to work and I'm stumped.
using System.Text.Json;
namespace JsonTest2;
public class Result
{
public string? Total { get; set; }
public string? Limit { get; set; }
public string? Start { get; set; }
protected List<Park>? Data { get; set; }
}
public class Park
{
public string? Id { get; set; }
}
internal class Program
{
var basepath = AppDomain.CurrentDomain.BaseDirectory;
var filepath = basepath.Split("\\bin")[0];
var filename = #$"{filepath}\NPS_response_small.json";
var jsonstr = File.ReadAllText(filename);
var response = JsonSerializer.Deserialize<Result>(jsonstr, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
}
This is the content of "NPS_response_small.json":
{
"total": "468",
"limit": "50",
"start": "0",
"data": [
{
"id": "77E0D7F0-1942-494A-ACE2-9004D2BDC59E"
},
{
"id": "6DA17C86-088E-4B4D-B862-7C1BD5CF236B"
},
{
"id": "E4C7784E-66A0-4D44-87D0-3E072F5FEF43"
}
]
}
you have to chanbe a protected attribute of property Data to a public. Json deserializer doesnt have any acces to this property
public List<Park>? Data { get; set; }
it would be much easier to use Newtonsoft.Json, but if you need protected for some reason, you can try this ( but I am not sure that it is a full replacement)
public List<Park>? Data { protected get; init ; }
[System.Text.Json.Serialization.JsonConstructor]
public Result (List<Park>? Data, string? Total, string? Limit, string? Start)
{
this.Data=Data;
this.Total=Total;
this.Limit=Limit;
this.Start=Start;
}

Json Parse in ASP.NET

I want to parse below JSON in ASP.NET.
{
"destination_addresses": [
"Address 1"
],
"origin_addresses": [
"Address 2"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "15.7 km",
"value": 15664
},
"duration": {
"text": "17 mins",
"value": 1036
},
"status": "OK"
}
]
}
],
"status": "OK"
}
I want to retrieve the text and value from a distance token. I was able to reach till elements.
var objectjson = JObject.Parse(response.Content);
dynamic dynJson = JsonConvert.DeserializeObject(objectjson["rows"].ToString());
var elements = dynJson[0].ToString();
var firstElement = JObject.Parse(elements);
How to parse the json further to reach to the distance token and then text and value?
Create a class like:
public class Distance {
public string text { get; set; }
public int value { get; set; }
}
public class Duration {
public string text { get; set; }
public int value { get; set; }
}
public class Element {
public Distance distance { get; set; }
public Duration duration { get; set; }
public string status { get; set; }
}
public class Row {
public List<Element> elements { get; set; }
}
public class Root {
public List<string> destination_addresses { get; set; }
public List<string> origin_addresses { get; set; }
public List<Row> rows { get; set; }
public string status { get; set; }
}
then, you can convert on it and construct your logic easylly
var myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
Sites references:
Json2Csharp
NewtonSoft
If you don't want to design a data model corresponding to your JSON, you can access nested JToken values using its item indexer:
var distance = objectjson["rows"]?[0]?["elements"]?[0]?["distance"];
var text = (string)distance?["text"];
var value = (decimal?)distance?["value"]; // Or int or double, if you prefer.
You can also use SelectToken() to access nested values:
var distance = objectjson.SelectToken("rows[0].elements[0].distance");
Notes:
There is no need to reformat and reparse the JSON simply to access nested data. I.e. JsonConvert.DeserializeObject(objectjson["rows"].ToString()) is superfluous and will harm performance.
I am using the null-conditional operator ?[] to access nested tokens in case any of the intermediate properties are missing. If you are sure the properties are never missing or would prefer to throw an exception, you can do
var distance = objectjson["rows"][0]["elements"][0]["distance"];
Demo fiddle here.
Take this sample json and:
Go to visual studio
In the menu -> Edit -> Paste Special -> Paste JSON and Classes
VS will generate the classes for you. It will generate the root type as Root, rename it to whatever you want or leave it as Root. Then you can simply deserialise your string into that class.
var rootObject = JsonConvert.DeserializeObject<Root>(response.Content);
// Simply use rootObject to access any property
var firstElement = rootObject.rows[0].elements[0];
// firstElement.distance.text
// firstElement.distance.value
// firstElement.duration.text
// firstElement.duration.value
// firstElement.status
You can traverse the data this way:
' strBuf = your json string
Dim jOb As JObject = JObject.Parse(strBuf)
Dim MyDistance As JToken = jOb.SelectToken("rows[0].elements[0]")
After above, then
Text = MyDistance.SelectToken("distance.text").ToString
value = MyDistance.SelectToken("distance.value").ToString
Status = MyDistance.SelectToken("status").ToString
The above will get you the 3 values. Note that each of the rows are repeating data, so it not clear if you have one string, and with to pull the values, or pull multiple values? If you need to pull repeating data, then above would change.
The above is vb, but it quite much the same in c#.

C# Json serialize different types

I'm trying to retrieve all data from a JSON file to my C# application.
But now the problem is that the field "info" in my json file is sometimes from the type string but it can also be the type object.
{
[
{
"id":"147786",
"canUpdate":true,
"canDelete":true,
"canArchive":true,
"hasChildren":false,
"info": "Test"
},
{
"id":"147786",
"canUpdate":true,
"canDelete":true,
"canArchive":true,
"hasChildren":false,
"info": [{"id"="1","messages":"true"}]
}
]
}
well my model you can see here below, when there are only strings in my json file i can retrieve the data without any exception but when there are also objects in the info field then i get the error can't convert the value.
Is there a way to fix this on an easy way?
public string id { get; set; }
public string canUpdate { get; set; }
public string info { get; set; }
As an option you can define the info as dynamic:
public dynamic info { get; set; }
Example
Consider the following json string:
string json = #"
[
{ 'P1': 'X', 'P2': 'Y' },
{ 'P1': 'X', 'P2': [
{'P11':'XX', 'P22':'YY'},
{'P11':'XX', 'P22':'YY'}]
}
]";
You can define such model to deserialize it:
public class C
{
public string P1 { get; set; }
public dynamic P2 { get; set; }
}
And deserialize it like this:
var obj = JsonConvert.DeserializeObject<C[]>(json);
Note
If the number of dynamic properties is too much then usually there is no point in creating the class and the following code will be enough:
var obj = (dynamic)JsonConvert.DeserializeObject(json);

Parse JSON array in C#

I'm trying to parse the following json array
[
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337197600,
"smtp-id": "<4FB4041F.6080505#sendgrid.com>",
"event": "processed"
},
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337966815,
"smtp-id": "<4FBFC0DD.5040601#sendgrid.com>",
"category": "newuser",
"event": "clicked"
},
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337969592,
"smtp-id": "<20120525181309.C1A9B40405B3#Example-Mac.local>",
"event": "processed"
}
]
I've not really used json format before, so it's all a little new. I found I can parse a single element easily, i.e.
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337197600,
"smtp-id": "<4FB4041F.6080505#sendgrid.com>",
"event": "processed"
}
dynamic stuff = JsonConvert.DeserializeObject(json);
Response.Write(string.Format("{0} = {1}<br />", "timestamp", stuff.timestamp));
//etc
But i'm struggling with how to get the individual elements into an array to loop through.
I though about splitting the sting on },{ but didn't have much luck with that. I imagine there's an easier way i'm missing.
Thank you.
Just deserialize the JSON as is and loop it...
dynamic stuff = JsonConvert.DeserializeObject(json);
foreach (var s in stuff)
{
Console.WriteLine(s.timestamp);
}
Fiddle: http://dotnetfiddle.net/0SthDp
You can create a class like this one, to accept all properties from the json string:
public class MyClass
{
public string email { get; set; }
public long timestamp { get; set; }
[JsonProperty("smtp-id")]
public string smtpid { get; set; }
public string category { get; set; }
[JsonProperty("event")]
public string evt { get; set; }
}
As you can notice there is JsonProperty attribute on the smtpid and evt properties, because you can not use the names in the json string as properties in C#.
Then just call the following line:
var list = JsonConvert.DeserializeObject<List<MyClass>>(json);
and you'll get a strongly typed list of objects that matches the json string.
Use JSON.Net to do this for you:
Create a class to hold the data (notice the attribute I put on smtp-id to handle characters C# doesn't like):
public class EmailEvent
{
public string Email { get; set; }
public int TimeStamp { get; set; }
[Newtonsoft.Json.JsonProperty(PropertyName="smtp-id")]
public string SmtpId { get; set; }
public string Event { get; set; }
public string Category { get; set; }
}
Then just deserialize it:
var events = Newtonsoft.Json.JsonConvert.DeserializeObject<List<EmailEvent>>(System.IO.File.ReadAllText(#"z:\temp\test.json"));
foreach (var ev in events)
{
Console.WriteLine(ev.SmtpId);
}
Create these two classes to hold your data:
public class SMTPEvent {
public string Email { get; set; }
public long TimeStamp { get; set; }
public string SmtpId { get; set; }
public string EventType { get; set; }
}
public class SMTPEvents {
public List<SMTPEvent> Events { get; set; }
}
Then you can call the following:
dynamic stuff = JsonConvert.DeserializeObject<SMTPEvents>(json);
To iterate you can then use:
foreach(SMTPEvent sEvent in stuff)
{
//whatever you want to do.
}
The advantage to this approach is having more type safety at run-time whilst having reusable objects if you're going to use them in other parts of your system. If not, you might want to use the simpler dynamic approach as suggested by others.
Also, remember to use the JsonProperty attribute to specify the actual property name as specified in your JSON string if you cannot / are not going to create fields that have the exact name as in your JSON.
The first level - stuff - is an Array of objects. It is the objects, or elements in said array, which contain a timestamp field.
Consider the following:
dynamic items = JsonConvert.DeserializeObject(json);
foreach(dynamic item in items) {
/* use item.timestamp */
}

JavaScriptSerializer and MVC - struggling with JSON

I've been trying to figure out why some of my tests haven't been working (TDD) and managed to track it down to serialization of a class, but I'm not sure why it's not working. There are two flavours, a simple version and a more complex version, the slightly more complicated one involves having an array of values within the Parameter.Value.
The simple version, I've got a class that can be serailzied using the JavaScriptSerializer (I'm assuming this is how MVC works when it generates JSON). The structure it produces looks like this:
{
"Name": "TestQuery",
"QueryId": 1,
"Parameters": [
{
"Name": "MyString",
"DataType": 0,
"Value": "A String",
"IsArray": false
}],
"Sql": "SELECT * FROM Queries"
}
There are 3 C# classes Query, ParameterCollection (which is a KeyedCollection<String, Parameter>) and a Parameter. All of these are marked up with DataContract/DataMember attributes and serialize via the DataContractSerializer without any problem.
The JavaScriptSerializer however, serializes the object correctly to the JSON above, but upon deserialization I have no Parameters, they just seem to get missed off.
Does anyone have any idea why these fails, and what I might be able to do to fix it?
Why KeyedCollection<String, Parameter>? You have an array, not dictionary, so your JSON should match the following structure:
public class Query
{
public int QueryId { get; set; }
public string Name { get; set; }
public string Sql { get; set; }
public Parameter[] Parameters { get; set; }
}
public class Parameter
{
public string Name { get; set; }
public int DataType { get; set; }
public string Value { get; set; }
public bool IsArray { get; set; }
}
and then you will be able to deserialize it without any problems:
var serializer = new JavaScriptSerializer();
var json = #"
{
""Name"": ""TestQuery"",
""QueryId"": 1,
""Parameters"": [
{
""Name"": ""MyString"",
""DataType"": 0,
""Value"": ""A String"",
""IsArray"": false
}],
""Sql"": ""SELECT * FROM Queries""
}";
var query = serializer.Deserialize<Query>(json);
Also you can get rid of [Data*] attributes from your view models, they are not used by the JavaScriptSerializer class.

Categories

Resources