How I can deserialize Json into Dictionary<String,List<String>> - c#

I have a sample Json
[{"_2":["HR Data","Reformed (Master File)"]}]
and I am trying to deserialize it into below model
public class ExploreCriteria
{
public Dictionary<String, List<String>> Explore { get; set; }
}
this is what I have tried so far
ExploreCriteria Explore = new ExploreCriteria();
Explore = JsonConvert.DeserializeObject<ExploreCriteria>(JsonStr);
but it says
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'DataModels.ExploreCriteria' because the type requires a JSON object
(e.g. {"name":"value"}) to deserialize correctly.

The provided JSON and your ExploreCriteria class do not describe the same structure.
Your JSON structure is an array that contains a key with an array value. So you can either remove the square brackets to
{"_2":["HR Data","Reformed (Master File)"]}
then your ExploreCriteria is fitting. Or you can change the JsonConvert call to
var JsonStr = "[{\"_2\":[\"HR Data\",\"Reformed(Master File)\"]}]";
ExploreCriteria Explore = new ExploreCriteria();
var data = JsonConvert.DeserializeObject<IEnumerable<Dictionary<String, List<string>>>>(JsonStr);
Explore.Explore = data.FirstOrDefault();

List<KeyValuePair<string, List<string>>> uploadedfiles =
JsonConvert.DeserializeObject<List<KeyValuePair<string, List<string>>>>(json);
use keyvaluepair class instead of dictionary.

Related

how to get Json values which are not in a class using C#?

I have the following problem:
I am a C# beginner and I want to create a weather app using the OpenWeatherApi.
The response of the api looks like this (it´s just an example):
[
{
"name": "London",
"lat": 51.5085,
"lon": -0.1257,
"country": "GB"
},
I want to get the lat and lon values.
My C# code looks like this:
public class CoordinatesResponse
{
public double Lat { get; set; }
public double Lon { get; set; }
}
private static string _coordinatesResponse;
static void ExtractCoordinatesFromJson()
{
CoordinatesResponse coordinatesresponse = JsonConvert.DeserializeObject<CoordinatesResponse>(_coordinatesResponse);
Console.WriteLine(coordinatesresponse.Lat);
Console.WriteLine(coordinatesresponse.Lon);
}
My error is the following:
Unhandled exception. Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WeatherApp.CoordinatesResponse' 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 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.
What do I wrong?
Your problem is in the type. Been an array, you must use List<CoordinatesResponse>:
static void ExtractCoordinatesFromJson()
{
var coordinatesresponses = JsonConvert.DeserializeObject<List<CoordinatesResponse>>(_coordinatesResponse);
foreach (var coordinatesresponse in coordinatesresponses)
{
Console.WriteLine(coordinatesresponse.Lat);
Console.WriteLine(coordinatesresponse.Lon);
}
}
To solve the issue " Cannot deserialize the current JSON array (e.g. [1,2,3])"
Follow the steps:
Go to any website that convert JSON to C# (e.g. https://json2csharp.com/).
Paste your JSON data in the JSON section and click on generate C# link button.
It will generate the object to deserialize the json array.
e.g. JsonDataService myData = JsonConvert.DeserializeObject(json);
The above object can be used to manipulate the JSON string object.

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);

C# - Cannot deserialize the current JSON array

I have this code:
string json2 = vc.Request(model.uri + "?fields=uri,transcode.status", "GET");
var deserial = JsonConvert.DeserializeObject<Dictionary<string, object>>(json2);
var transcode = deserial["transcode"];
var serial = JsonConvert.SerializeObject(transcode);
var deserial2 = JsonConvert.DeserializeObject<Dictionary<string, object>>(serial);
var upstatus = deserial2["status"].ToString();
The json I get from the server is:
{
"uri": "/videos/262240241",
"transcode": {
"status": "in_progress"
}
}
When running it on VS2017, it works.
But on VS2010 I get the following error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'System.Collections.Generic.Dictionary`2[System.String,System.Object]'
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 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.
Path '', line 1, position 1.
I am using Newtonsoft.Json.
Any idea?
Your received json data is not a Dictionary<string, object>, it is a object
public class Transcode
{
public string status { get; set; }
}
public class VModel
{
public string uri { get; set; }
public Transcode transcode { get; set; }
}
You can use this object:
var deserial = JsonConvert.DeserializeObject<VModel>(json2);
instead of:
var deserial = JsonConvert.DeserializeObject<Dictionary<string, object>>(json2);
The best answer was deleted for some reason, so i'll post it:
var deserial = JsonConvert.DeserializeObject<dynamic>(json2);
string upstatus = string.Empty;
upstatus = deserial.transcode.status.ToString();
If your model is not well defined or it is dynamic, then use:
var deserial = JsonConvert.DeserializeObject<dynamic>(json2);
or you can try to use:
JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json2);

Newsoft Json deserialize into products Collection not working

I am creating a windows phone silver light 8 app.
I have a Json string and I am trying to convert it into a List of objects and each object is a object of a class classed "Product" and list is supposed to be products. ultimately I want it to convert into Observable collection so that I can bind that collection to my listbox in my windows Silverlight phone app.
Here is my class
public class Product
{
public string _id { get; set; }
public string code { get; set; }
public string name { get; set; }
public string imgAddress { get; set; }
public int queryCount { get; set; }
}
Here is code to deserialize the json
var PDS = "{\"products\":[{\"_id\":\"58b2\",\"code\":\"59034\",\"name\":\"somename1\",\"imgAddress\":\"https://someimageurl/.../.jpg\",\"queryCount\":0},{\"_id\":\"58b3\",\"code\":\"59035\",\"name\":\"somename2\",\"imgAddress\":\"https://someimageurl2/.../.jpg\",\"queryCount\":1}]}";
var pds = JsonConvert.DeserializeObject<List<Product>>(PDS);
//PDS is actually very long string and the array products has a lot of objects but I am only writing 2 products here for simplicity.
Here is my collection for binding
public ObservableCollection<Product> Products { get; set; }
ERRORS
>> First I was getting parsing error so I escaped all quotes within the string like this \"
**>>**But then it was only converting to a normal string like object but I want to convert to a collection of products of type "Product"
>> Exception
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[PivotApp1.Product]' 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) 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.
Path 'products', line 1, position 12.
Thanks in advance
You can deserialize it this way (but you'll have somehow to reformat your JSON string):
from
var PDS = "{"products":[{"_id":"58b2","code":"59034","name":"somename1","imgAddress":"https://someimageurl/.../.jpg","queryCount":0},{"_id":"58b3","code":"59035","name":"somename2","imgAddress":"https://someimageurl2/.../.jpg","queryCount":1}]}";
//PDS is actually very long string and the array products has a lot of objects but I am only writing 2 products here for simplicity.
to
var PDS = "[{'_id':'58b2','code':'59034','name':'somename1','imgAddress':'https://someimageurl/.../.jpg','queryCount':0},{'_id':'58b3','code':'59035','name':'somename2','imgAddress':'https://someimageurl2/.../.jpg','queryCount':1}]";
//PDS is actually very long string and the array products has a lot of objects but I am only writing 2 products here for simplicity.
Then
var pds = JsonConvert.DeserializeObject<List<Product>>(PDS);
More infos --> Deserialize a collection
No need of creating another class as suggested!
EDIT:
Actually you get this exception because your JSON string represents an object 'products' containing a list of 'Product' and this doesn't directly relate to your root class.
This is what your current JSON look like:
Your JSON string result should be something like that instead:
var PDS = "[{'_id':'58b2','code':'59034','name':'somename1','imgAddress':'https://someimageurl/.../.jpg','queryCount':0},{'_id':'58b3','code':'59035','name':'somename2','imgAddress':'https://someimageurl2/.../.jpg','queryCount':1}]";
Represented as following (notice the slight difference):
Using this JSON string, it will work with no exception raised:
var pds = JsonConvert.DeserializeObject<List<Product>>(PDS);
Or, if you can't change the resulting JSON string in PDS, you can do what J. Tuc suggested (via a new "RootClass").
your JSON string had to be changed to get the code to compile:
var PDS = "{'products':[{'_id':'58b2','code':'59034','name':'somename1','imgAddress':'https://someimageurl/.../.jpg','queryCount':0},{'_id':'58b3','code':'59035','name':'somename2','imgAddress':'https://someimageurl2/.../.jpg','queryCount':1}]}";
You need another object with a collection of Product as a property called products in order to deserialize your JSON
This may not be the best solution but it works:
Create another class:
public class RootObject
{
public List<Product> products;
}
use this code to deserialize your JSON:
var pds = JsonConvert.DeserializeObject(PDS, typeof(RootObject));
if you are in control of your JSON string you might consider changing it to this (removing 'products' property and ending up with just an array of products in the JSON string):
var PDS = "[{'_id':'58b2','code':'59034','name':'somename1','imgAddress':'https://someimageurl/.../.jpg','queryCount':0},{'_id':'58b3','code':'59035','name':'somename2','imgAddress':'https://someimageurl2/.../.jpg','queryCount':1}]";
Then you might be able to use the solution proposed by TaiT's (deserializing directly to a List of Product) :
var pds = JsonConvert.DeserializeObject<List<Product>>(PDS);

.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);

Categories

Resources