I have the following JSON coming back from a remote API (I cannot modify the JSON returned)
{
"APITicket": {
"location": "SOMEVALUE",
"ticket": "SOMEVALUE"
}
}
Now using JSON.Net to convert to this to a model I have to create 2 models.
public class TicketModel
{
public string location { get; set; }
public string ticket { get; set; }
}
public class TicketContainer
{
public TicketModel APITicket { get; set; }
}
and do something like..
var myObject = JsonConvert.DeserializeObject<TicketContainer>(this.JSONResponse);
and this works well - my problem arises when I have around 50 calls to make to the API and really dont fancy creating a second 'Container' for each. Is there a way to bind the example above directly to the TicketModel?
You can do it this way:
var json = #"
{
'APITicket': {
'location': 'SOMEVALUE',
'ticket': 'SOMEVALUE'
}
}";
//Parse the JSON:
var jObject = JObject.Parse(json);
//Select the nested property (we expect only one):
var jProperty = (JProperty)jObject.Children().Single();
//Deserialize it's value to a TicketModel instance:
var ticket = jProperty.Value.ToObject<TicketModel>();
use Newtonsoft's JArray to customize ur json before deserialize
public List<APITicket> JsonParser(string json)
{
Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.Parse(json);
var list = new List<APITicket>();
foreach(var item in jArray)
{
list.Add(
new APITicket { location = item["APITicket"]["location"],
ticket = item["APITicket"]["ticket"]
}
);
}
return list;
}
Modify the JSON so it looks like this
{
"location": "SOMEVALUE",
"ticket": "SOMEVALUE"
}
and do
List<TicketModel> tickets = JsonConvert.DeserializeObject<List<TicketModel>>(this.JSONResponse);
or even
Dictionary<string, string> tickets = JsonConvert.DeserializeObject<Dictionary<string, string>>(this.JSONResponse);
so you don't need any models.
Related
I am struggling to convert below input json to output json as this is what is the required format to call
hubspot api to submit a form. I am writing this using .net core within Azure function.
Input Json
{
"Email":"myemail#test.com",
"Phone":"12345678",
"Address":"address 1"
}
Output json
{
"fields": [
{
"name": "Email",
"value": "myemail#test.com"
},
{
"name": "Phone",
"value": "12345678"
},
{
"name": "Address",
"value": "address 1"
}
]
}
I converted the input json to dictionary using
IDictionary<string, string> dictionary = JsonConvert.DeserializeObject<IDictionary<string, string>>(inputJson);
but that gives me key value pair instead of name value pair.
I would like the output as detailed above.
Any help/example code would be highly appreciated.
You could create your own "NameValuePair" class/struct if you don't want "Key" as the field name:
public class FieldContainer
{
[JsonProperty("fields")]
public IEnumerable<NameValuePair> Fields { get; set; }
}
public struct NameValuePair
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
public NameValuePair(string name, string value)
{
Name = name;
Value = value;
}
}
And then do like you've already done, but converting the KeyValuePairs into your own struct:
var inJson = #"{
""Email"":""myemail#test.com"",
""Phone"":""12345678"",
""Address"":""address 1""
}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(inJson);
var container = new FieldContainer
{
Fields = dict.Select(pair => new NameValuePair(pair.Key, pair.Value))
};
var outJson = JsonConvert.SerializeObject(container);
See this fiddle for a demonstration.
Easiest way to do this would be to take the json and convert it to Dictionary<string, string>. Loop over each KeyValuePair and create a list of Fields using LINQ. Once you have the List of fields, create your RootObject.
public class RootObject
{
[JsonProperty("fields")]
public List<Field> Fields { get; set; }
}
public class Field
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
// Create a dictionary
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonStr);
// Create a list of Fields
List<Field> fields = dict.Select(x => new Field() { Name = x.Key, Value = x.Value }).ToList();
// Create the final Object.
RootObject rootObj = JsonConvert.SerializeObject(new RootObject() { Fields = fields });
Alternative solution, using JObject.Parse() to parse the original JSON, then iterate its Properties to create an array of JObjects with different names and values.
The resulting IEnumerable<JObject> is then converted to a JArray, used to create the final fields object.
var jObj = JObject.Parse(json);
var newObjects = jObj.Properties().Select(p => new JObject {
new JProperty("name", p.Name),
new JProperty("value", p.Value)});
var fields = new JObject() {
{ "fields", JArray.FromObject(newObjects)}
};
Console.WriteLine(fields);
I have below requirement, where I need to merge two Json objects using JSON.NET.
Below is the sample code
string jsonText = #"
{
""food"": {
""fruit"": {
""apple"": {
""colour"": ""red"",
""size"": ""small""
},
""orange"": {
""colour"": ""orange"",
""size"": ""large""
}
}
}
}";
var foodJsonObj = JObject.Parse(jsonText);
var foodJsonToken = foodJsonObj.SelectToken("food.fruit") as JObject;
var bananaJson = JObject.Parse(#"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}, ""simpletype"":""simplevalue"", ""orange"":{ ""newprop"": ""newpropvalue"" } }");
var bananaToken = bananaJson as JObject;
foreach (var token1 in bananaToken)
{
**var existingTokens = foodJsonToken.Children();
foreach (var item in existingTokens)
{
var existingObject = item as JObject;
}
if (existingTokens.Contains(token1.Key))
{
foodJsonToken.Merge(token1, new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Union
});
}**
else
{
foodJsonToken.Add(token1.Key, token1.Value);
}
}
json = foodJsonToken.ToString();
In the above example, I want to merge banana json into food json
above code is working without hightlighted code, if the bananajson does not have “orange” property which already in food json
if both have similar set of properties, above code is not working.
Is there any way to using linq to find existing element, if that exists, I want to merge the json else it going to update source with new properties.
Regards,
Amar
If the structure of you main json is always the same you can create two classes:
a) Main class Food with collections of fruits
b) Fruit class with fields: colour and size
You can easily add/remove any fruit from the Food class collection.
You can serialize/deserialize Food or Fruit class using NewtonSoft library.
The whole code should look like:
[DataContract]
class Food
{
[DataMember]
public ArrayList<Fruit> Fruit { get; set; }
}
[DataContract]
class Fruit
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Colour { get; set; }
[DataMember]
public string Size{ get; set; }
}
Example usage:
var sampleFoodInstanc = new Food();
sampleFoodInstance.Fruit.Add( new Fruit() { Name: "Apple", Colour: "Red", Size: "Big" } );
// serialize process
var sz = JsonConvert.SerializeObject( sampleFoodInstance );
// deserialize process
JsonConvert.DeserializeObject<Food>( sz );
I do a request to a api that I'm using and this is the response that I get back.
{ "id": 1139, "performanceStatus": "OK", "availabilityStatus": "OK" }
I would like to convert this response in a list where I then can use a for/foreach loop and later can use linq and SelectMany to create a whole new list.
I got this far, but I am stuck the code is not hitting the var "newJson"..
Can someone help me out?
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
dynamic parsedJson = JObject.Parse(json);
foreach (var j in parsedJson)
{
j.Replace(JObject.FromObject(
new {
id = j.id,
performance = j.performanceStatus,
availability = j.availabilityStatus
}));
}
var newJson = parsedJson.ToString();
Later I would like to Deserialize it into a strongly typed class. Like so
boi = await Task.Run(() => JsonConvert.DeserializeObject<Boi>(newJson)).ConfigureAwait(false);
Here is the strongly typed class
public class Boi
{
public int Id { get; set; }
public string PerformanceStatus { get; set; }
public string AvailabilityStatus { get; set; }
}
public class NewBoi
{
public List<Boi> eeg { get; set; }
}
You could do this:
var jsn = "{ \"id\": 1139, \"performanceStatus\": \"OK\", \"availabilityStatus\": \"OK\" }";
var bois = new List<Boi> { JsonConvert.DeserializeObject<Boi>(jsn) };
var newBoi = new NewBoi() { eeg = bois };
Although I would question the need for the NewBoi class - you could just work with the List.
To deserialize to a well known type use
JsonConvert.Deserialize<T>(jsonString,new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
where T is your well known type.
We have DTO class like this:
public class DTO
{
public int Number { get; set; }
public string Title { get; set; }
public Dictionary<string, string> CustomFields { get; set; }
}
I want to serialize/deserialize DTO by ServiceStack to JSON where CustomFields is expanded as DTO fields. For example
new DTO
{
Number = 42
Title = "SuperPuper"
CustomFields = new Dictionary<string, string> {{"Description", "HelloWorld"}, {"Color", "Red"}}
}
serialize to
{
"Number":42,
"Title":"SuperPuper",
"Description":"HelloWorld",
"Color":"Red"
}
How can I achieve this?
All dictionary fields must be represented as JSON object fields during serialization.
All fields of incoming JSON object that are not fields of DTO must be put to Dictionary during deserialization.
If you use the Newtonsoft library you can do this:
DTO Test = new DTO
{
Number = 42,
Title = "SuperPuper",
CustomFields = new Dictionary<string, string> { { "Description", "HelloWorld" }, { "Color", "Red" } }
};
String Json = Newtonsoft.Json.JsonConvert.SerializeObject(Test);
Json = Json.Replace("\"CustomFields\":{", "");
Json = Json.Replace("}}", "}");
The resulting json string looks like this:
{"Number":42,"Title":"SuperPuper","Description":"HelloWorld","Color":"Red"}
[Edit]
I'm not going to do ALL your work...this should get you started:
// to reconstruct the object
Newtonsoft.Json.Linq.JObject MyObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Json) as Newtonsoft.Json.Linq.JObject;
// Create a new object here.
foreach( var Token in MyObject)
{
// sample
if (Token.Key == "Number")
{
// populate the fields of the new object with Token.Value
}
}
How can I deserialize:
{
"data": [
{"ForecastID":8587961,"StatusForecast":"Done"},
{"ForecastID":8588095,"StatusForecast":"Done"},
{"ForecastID":8588136,"StatusForecast":"Done"},
{"ForecastID":8588142,"StatusForecast":"Pending"}
]
}
to
class RawData
{
public string data { get; set; }
}
So, I just want to have
[
{"ForecastID":8587961,"StatusForecast":"Done"},
{"ForecastID":8588095,"StatusForecast":"Done"},
{"ForecastID":8588136,"StatusForecast":"Done"},
{"ForecastID":8588142,"StatusForecast":"Pending"}
]
as value of property data of RawData's class instance.
Using Json.Net
var obj = (JObject)JsonConvert.DeserializeObject(json);
var newJson = obj["data"].ToString();
or using built-in JavaScriptSerializer
var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
var newjson = new JavaScriptSerializer().Serialize(dict["data"]);
It would have made far much more sense to deserialize this JSON structure to:
public class Forecast
{
public IEnumerable<ForecastData> Data { get; set; }
}
public class ForecastData
{
public int ForecastID { get; set; }
public string StatusForecast { get; set; }
}
which is pretty trivial with the JavaScriptSerializer class that's built into the framework:
string json = "your JSON data here";
IEnumerable<ForecastData> data = new JavaScriptSerializer()
.Deserialize<Forecast>(json)
.Data;
or if you don't want to define models you could do that:
dynamic result = new JavaScriptSerializer().DeserializeObject(json);
foreach (var item in result["data"])
{
Console.WriteLine("{0}: {1}", item["ForecastID"], item["StatusForecast"]);
}