serialize / deserialise json array key value pair - c#

I'm looking to construct a C# object to produce the following JSON array:
["Key":"SomeKeyValue", "Key":"SomeKeyValue"]
Using a list gives me the array I'm after, but with a object name in the resulting JSON:
Public Class SomeOtherClass
{
public string Key {get; set;}
}
Public Class SomeObject
{
public List<SomeOtherClass> PropertyName { get; set; }
}
// JSON
{"PropertyName":[ {"Key":"SomeValue"} ] }
I need to drop the name of the object in the resulting JSON. Using a Dictionary<string,string> gives me what I'm after but with the Object syntax {} in the JSON instead if the Array []:
{
...
}
Trying to avoid custom serializer and contracts here if possible. I'm sure that NewtonSoft must have some magic attribute here?
Found a few related questions on the net, but none that resolves removing the property name. Any suggestions?

From looking at a XML to JSON converter, the conversion from the XML:
<ClassName>
<!--Zero or more repetitions:-->
<key>value1</key>
<key>value2</key>
<key>value3</key>
</ClassName>
has the JSON equivalent of:
"ClassName": {
"key": [
"value1",
"value2",
"value3"
]
}
Using this for now until I can test it on more 3rd party systems that I need to integrate with.

Related

JSON deserialization returns {null,null} for KeyValuePair

I've declared the below key:value pair in JSON:
"saleParameters": [
{"saleName":"FlashSale2018"},
]
I'm mapping the above using the below property in my contract class:
[JsonProperty("saleParameters")]
public IEnumerable<KeyValuePair<string,string>> SaleParameters { get; set; }
But for some reason, I always receive null values in SaleParameters after deserialization. I'm using NewtonSoft.JSON for JSON serialize/deserialize, code is running on .net core.
Any idea on why this is happening and how to solve this ?
The problem is that your current code expects JSON like this:
"saleParameters": [
{"Key": "saleName", "Value": "FlashSale2018"}]
]
You should use a dictionary instead:
public IEnumerable<IDictionary<string,string>> SaleParameters { get; set; }
This will deserialize "saleName" as they key and "FlashSale2018" as the value. And, if you really need IEnumerable<KeyValuePair<string, string>>, you can call SaleParameters.SelectMany(p => p). ToEnumerable().

Cannot deserialze the current JSON array into type

I'm trying to deserialize following JSON data :
{
"bids": [
[
"392031.00000000",
"0.00254444"
],
[
"390000.00000000",
"0.52917503"
],
......
],
"asks": [
[
"392999.00000000",
"1.00000000"
],
[
"393000.00000000",
"0.31572236"
],
.....
]
}
I've looked into similar question such as this one, but I'm not getting close result and also noticed that in that question the structure of JSON is not similar.
My code for deserialization is as below
public class OrderBookElement
{
// I've also tried below commented code
//[JsonProperty(PropertyName = "0")]
//public double price { get; set; }
//[JsonProperty(PropertyName = "1")]
//public double volume { get; set; }
List<double> values;
}
public class OrderBookResponse
{
[JsonProperty(PropertyName = "bids")]
List<OrderBookElement> bids { get; set; }
[JsonProperty(PropertyName = "asks")]
List<OrderBookElement> asks { get; set; }
}
Below is code that I use for deserialization
var ordBook = JsonConvert.DeserializeObject<OrderBookResponse>(jsonResponse);
This gives me error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'RestAPI.OrderBookElement' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
The JSON you've shown would be represented by:
public class OrderBookResponse
{
[JsonProperty("bids")]
public List<List<string>> Bids { get; set; }
[JsonProperty("asks")]
public List<List<string>> Asks { get; set; }
}
The bids and asks properties in the JSON are each just an array of arrays of strings.
I'd suggest deserializing to a model which matches the JSON, then convert that into a more useful model separately. It may be possible to apply attributes to your class to persuade Json.NET to do what you want, but I tend to think that by the time there's a significant discrepancy (not just the property names), it's worth separating the two models out, one for serialization and one for use within the rest of your code.

C# deserailize json in non standard format

I am consuming a web service that will calculate tax. The problem is I don't always get the data back in exactly the same formatn (see example below). When I deserialize the data my code throws an exception. Any tips on what I can do to allow the deserialization to handle a single element or an array of a single element? FYI, I get back a lot more data in addition to the tax, but I am only showing the tax part to keep it simple.
Sometimes I get the data like this:
{
"data": {
"tax": [{
"amount": 0.00,
"category": 0.0
}]
}
}
Sometimes I get it like this:
{
"data": {
"tax": {
"amount": 336.01,
"category": 0.0
}
}
}
Here is my class:
public class Tax
{
public float amount { get; set; }
public float category{ get; set; }
}
I am thinking about adding an [XmlIgnore] attribute and manually deserailizing to get the tax data, but I would like to stay away from that if possible.
Not sure how XmlIgnore would help with your JSON serialization, but i would suggest using Newtonsoft.Json to deserialize your payload to JObject. Then you can use Linq to JSON to investigate the result and perhaps manually instantiate your own object based on the type of "tax" property (JArray or JObject)
see LINQ to JSON for more info.
Make two (or more) different classes, then use the one that doesn't throw an exception when you deseralize.
It looks like you could deseralize the array data using this class:
public class data
{
public Dictionary<string, double> tax { get; set; }
}
If that class successfully deserializes, you can then copy it over to the tax class, either manually, or by using Reflection.
I'd use JSON.Net (link to nuget). Then I'd get a JObject from JObject.Parse method and check whether the relevant child element is JObject or JArray. Then, I'd convert it to your data class (or a dynamic type)
dynamic taxData;
var json = JObject.Parse(response);
var rawTaxData = json["data"]["tax"];
if (rawTaxData is JObject)
{
taxData = JsonConvert.DeserializeObject(rawTaxData);
}
else if (rawTaxData is JArray)
{
var actualData = rawTaxData [0];
taxData = JsonConvert.DeserializeObject(actualData);
}
Also, just to be sure that your server actually returned data and not, for example, error message, use TryGetValue:
JToken dataToken;
if (!json.TryGetValue("data", out dataToken))
{
var rawTaxData = dataToken["tax"];
// ...
}

Deserialize object with dynamic type field

I'm using Json.NET library and the following data contract:
public class A
{
[JsonProperty("result")]
public B[] Result { get; set; }
}
The problem is that JSON that should be parsed can be in two different formats (bad designed external system API).
Option 1:
{
result: [ /* B objects definitions here */ ]
}
Option 2 (weird):
{
result: "No results"
}
How to continue using JsonConvert deserializer and parse both options? How to redefine the contract? The second option should resolve to empty Bs array or null.

Deserializing Json with numbered keys in ServiceStack

I have such Json:
{
data:{
"50":{"id":"50","name":"test", etc...},
"51":{"id":"51","name":"test", etc...},
"53":{"id":"53","name":"test", etc...},
...
}
}
What is the correct way to deserialize this Json?
[UPDATED]
I think I must to adjust my question. Is it possible to parse Json using class with description of objects. E.g. I have such class and Json which I parse with .FromJson():
public class Data
{
public ...
}
public class Category
{
public int Id{get;set;}
public string Name{get;set;}
}
What should be instead three dots?
Your json contains an object O. This object has a member data that is a dictionary from strings or ints to your category objects. So try something like:
class Root
{
public Dictionary<int, Category> data;
}
var o = JavaScriptSerializer.Deserialize<Root>(json);
If you are using servicestack.text just do
var v = myJson.FromJson();
Don't forget that servicestack is best used when serialization also made with servicestack.
the best way to deserialize Json object to c# class in JSON.NET project (found on codeplex)
the deserialize example is:
JsonConvert.DeserializeObject<Category>(jsonString);

Categories