Deserialize JSON response using Newtonsoft.Json - c#

I have a web service which return response in JSON format as below.
{"123":{"Name":"Abcd", "Age":"30"},"231":{"Name":"xyz", "Age":"20"}, "543":{"Name":"pqr", "Age":"35"}}
I want to deserialize this response in C# and wants to display it.
How can I do with Newtonsoft.Json library.
Please help me.

I'm going to assume that "123", "231", and "543" are identifiers and not constant property names. In that case what you have is a dictionary of objects. First, define a class that maps to the object.
public class Something
{
public string Name { get; set; }
public string Age { get; set; }
}
Then deserialize into a dictionary of those objects.
var whatever = JsonConvert.DeserializeObject<Dictionary<string, Something>>(json);

Related

Cannot identify data structure from JSON to deserialize into object

Having issue with deserializing json string into object.
The main issue is that I can not identify what type of object this string represents:
string jsonDataText = #"{""sun"":""heat"", ""planet"":""rock"", ""earth"":""water"", ""galaxy"":""spiral""}";
It looks like List of KeyValuePair objects, but when I try to deserialize by using Newtonsoft.Json:
var clone = JsonConvert.DeserializeObject<List<KeyValuePair<string,string>>>(jsonDataText);
I have got an exception:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[System.Collections.Generic.KeyValuePair`2[System.String,System.String]]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Had also tried with Maps and string(multidimensional) arrays but got the same exception...
It looks like Dictionary< string,string > to me.
JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonDataText);
With using JObject its easy to read any key/value pair from JSON.
So you no more need to identify what the type of your key/value pair in your json.
string jsonDataText = #"{""sun"":""heat"", ""planet"":""rock"", ""earth"":""water"", ""galaxy"":""spiral""}";
//Parse your json to dictionary
Dictionary<string, string> dict = JObject.Parse(jsonDataText).ToObject<Dictionary<string, string>>();
You need to add this namespace to your program => using Newtonsoft.Json.Linq;
Output:
It looks like to me as a simple class.
public class MyClass
{
[JsonProperty("sun")]
public string Sun { get; set; }
[JsonProperty("planet")]
public string Planet { get; set; }
[JsonProperty("earth")]
public string Earth { get; set; }
[JsonProperty("galaxy")]
public string Galaxy { get; set; }
}
Deserialize:
var clone = JsonConvert.DeserializeObject<MyClass>(jsonDataText);

Deserializing an unnamed array

I am having difficulty writing the appropriate annotations to represent data which is returned from a JSON Get request which returns data like so:
[{"ProductCode":"0129923083091","Description":"DIESEL ","SalesLitres":6058.7347,"SalesValue":6416.2000},{"ProductCode":"0134039344902","Description":"UNLEADED ","SalesLitres":3489.8111,"SalesValue":3695.7100},
...
]
(ellipsis above just indicating that I could have variable number of these items returned)
In my model class (I am using MVVM approach for a Xamarin project but that's not over relevant here) I am using annotations to represent the model attributes
namespace App8.Models
{
public class ReportRow
{
[JsonProperty("ProductCode")]
public string ProductCode { get; set; } = string.Empty;
[JsonProperty("Description")]
public string Description { get; set; } = string.Empty;
[JsonProperty("SalesLitres")]
public double SalesLitres { get; set; } = 0.0;
[JsonProperty("SalesValue")]
public double SalesValue { get; set; } = 0.0;
}
}
I would like to annote another class which shows the container/contained relationship. However, I coming unstuck as there is no JSON attribute to provide in the annotation to represent the "root" of the returned collection.
I'd have no problem mapping the JSON to an object model for any JSON arrays which are named within the returned JSON. In that case I could create another class with a named JSON attribute which contained a C# List but I am trying to provide an appropriate model mapping for JSON which returns a list of items within an unnamed array.
Any ideas how I could approach this?
To deserialize that JSON, use:
JsonConvert.DeserializeObject<List<ReportRow>>(json)
(or any variant you wish, the key here is asking to deserialize a ICollection of ReportRow. It could be your own class implementing ICollection, or any of the builtins)
The same idea follows to JsonTextReader or whatever other means of deserializing JSON.NET offers. Just use a ICollection<YourType> as target type.

.NET Json Serialization Exception for C#

I'm using JSON.net in C# for an Excel VSTO Add in and pulling in JSON via web service.
I have verified the JSON I pull is valid (online JSON Validator) but am unable to convert the JSON into Objects in C# to use.
When I run the code below I get the exception below.
Any ideas on who I can covert the JSON correctly?
Exception:
Newtonsoft.Json.JsonSerializationException:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'Bliss.Ribbon1+RootObject[]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type
(e.g. not a primitive type like integer, not a collection type like an array or List<T>)
that can be deserialized from a JSON object.
JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Code:
public async Task<string> getline()
{
<--- Set Client, Execute Request --->
//JSON content shown below
string content = await response.Content.ReadAsStringAsync();
RootObject[] dims = JsonConvert.DeserializeObject<RootObject[]>(content);
return content;
}
public class RootObject
{
public List<string> ledger { get; set; }
public List<string> ledgerAlias { get; set; }
public List<string> entity { get; set; }
public List<string> entityAlias { get; set; }
public List<string> scenario { get; set; }
public List<string> period { get; set; }
public List<string> location { get; set; }
public List<string> measures { get; set; }
}
JSON:
{
"acc":["A","B"],
"accAlias":["ACE","BCE"],
"company":["PEP", "KO"],
"companyAlias":["Pepsi", "Coco-Cola"],
"scenario":["Sales", "Expenses"],
"year": ["2016","2017"],
"areaCode":["123","131","412"],
"clients":["32340-0120","3031-0211","3412-0142"]
}
The JSON represents a single instance of the object, not an array. So instead of this:
RootObject[] dims = JsonConvert.DeserializeObject<RootObject[]>(content)
use this:
RootObject dims = JsonConvert.DeserializeObject<RootObject>(content)
Conversely, if it should be an array, make the JSON itself an array (containing a single element) by surrounding it with brackets:
[{
"acc":["A","B"],
"accAlias":["ACE","BCE"],
"company":["PEP", "KO"],
"companyAlias":["Pepsi", "Coco-Cola"],
"scenario":["Sales", "Expenses"],
"year": ["2016","2017"],
"areaCode":["123","131","412"],
"clients":["32340-0120","3031-0211","3412-0142"]
}]
Edit: As others have also been pointing out, the properties on the JSON object don't actually match that class definition. So while it may "successfully" deserialize, in doing so it's going to ignore the JSON properties it doesn't care about and initialize to default values the class properties.
Perhaps you meant to use a different class? Or different JSON? Or rename one or more properties in one or the other?
Either way, the difference between a single instance and an array of instances is the immediate problem. But in correcting that problem you're going to move on to this next one.
The RootObject and the json are not compatible. You could deserialize using a dictionary. Try this:
var dims = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(content);

ServiceStack Json deserializing incorrectely

I've got a RequestDto, let's say Class A Dto, it contains a self defined type property:
// C# code
public Class MyObject
{
public string A { get; set; }
public string B { get; set; }
}
public Class ADto
{
public List<MyObject> MO { get; set;}
}
When I am trying to send the Dto using Json, the Json object looks like this:
{"MO":[{"A":"String","B":"a"},{"A":"String","B":"b"}]}
but the object I am receiving will be null.
However if I change the Json string into:
{MO:[{A:"String",B:"a"},{A:"String",B:"b"}]}
I lose the quotation marks on the objects' names and it works.
The correct format of Json should include those quotation marks right?
Why is this happening?
ServiceStack does serializes and deserializes valid JSON which requires every property name to be quoted however you're saying that the text below works:
{MO:[{A:"String",B:"a"},{A:"String",B:"b"}]}
However this isn't valid JSON, it instead looks like ServiceStack's JSV Format
You haven't mentioned where you're sending the JSV Format or have provided the Raw HTTP Request (for us to work it out), but I'm assuming if you're using Postman (mentioned in your comments) than you're trying to send JSON in the ?QueryString which isn't allowed.
But ServiceStack does support sending complex object graphs on the QueryString using JSV.
Since you're sending a complex type you'd either POST the request as either JSON or www-form-urlencoded Form Data or if you want to pass it in the QueryString you need to convert it to JSV.
In future please include the Raw HTTP Request as this question lacks any context on where you're changing the JSON string, how you're trying to use it or what's actually being sent, where you're sending it to, etc - making it impossible to guess what the issue is.
Change your class to
public Class MyObject
{
public string Mobile { get; set; }
public string Name { get; set; }
}
public Class ADto
{
public List<MyObject> MO { get; set;}
}
Then your json should be
{MO:[{Mobile:"0556604",Name:"Peter"},{Mobile:"4565466",Name:"John"}]}

Deserializing of Google's Translate API result in C#

I'm trying to deserialize Google's Translate API JSON response into an C# object using JavaScriptSerializer. However, it always says Type 'TranslateAPI.Models.Translations' is not supported for deserialization of an array.. I double checked whether I have correctly created models for this object and it seems right. Here are my models:
TranslateResult
public TranslateData data { get; set; }
TranslateData
public Translations translations { get; set; }
Translations
public TranslatedText[] translatedText { get; set; } // I have also tried List<TranslatedText> which also doesn't work
TranslatedText
public string translatedText { get; set; }
The json returned from Google looks like this:
{data: {
translations: [
{translatedText: "Hello world"}
]
}
Any idea what I'm doing wrong?
Thanks
PS. It could be useful to mention, that I'm deserializing it like so: TranslateResult translateResult = js.Deserialize <TranslateResult>(json);
I suspect you don't need the Translations class at all. You've got:
An object containing a data property
The data property value is an object containing a translations property
The translations property value is an array
Each element of the array is an object with a translatedText property
So that sounds to me like your TranslateData class should be:
TranslateData
public Translation[] translations { get; set; }
Translation // Renamed from TranslatedText
public string translatedText { get; set }
(I'd also recommend that you rename the properties to follow normal C# naming conventions, and then apply attributes to help with the JSON conversion if you need to. I haven't used JavaScriptSerializer for a while, but I'm sure it's feasible. You shouldn't need to work with nasty property names in your C# code.)

Categories

Resources