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);
Related
Given the following JSON samples, what is the best way to parse this in c# .NET?
{"data":{"5":{"isDeleted":"false","day":"THU"}},"action":"edit"}
{"data":{"7":{"isDeleted":"false","name":"alex"}},"action":"edit"}
{"data":{"90":{"isDeleted":"true","job":"software"}},"action":"edit"}
I have looked into JSON serializing into an object but because the data could be different each time i can't map it directly to a model.
So the model for this could be
public class Record
{
public Dictionary<string, Dictionary<string, string>> Data { get; set; }
public string Action { get; set; }
}
You can deserialize the JSON into a dynamic object, which allows you to access the properties of the JSON object without having to define a specific model with JsonSerializer of System.Text.Json:
string jsonString = "{\"data\":{\"5\":{\"isDeleted\":\"false\",\"day\":\"THU\"}},\"action\":\"edit\"}";
dynamic jObject = JsonSerializer.Deserialize<dynamic>(jsonString);
string action = jObject .action;
dynamic data = jObject .data;
string isDeleted = data["5"].isDeleted;
string day = data["5"].day;
I need to deserialize my JSON, which looks like this:
{
"cart.empty.title":"Il tuo carrello \u00e8 vuoto",
"returns.confirmation.status.step1.next.arbitration":"A breve riceverai un\u0027email con le istruzioni su come effettuare il reso.",
"returns.home_pickup.address.form.title":"Dove ritireremo i tuoi prodotti?"
}
I tried to do it like this:
string apiResponse = response.Content.ReadAsStringAsync().Result;
drupalRecords = JsonConvert.DeserializeObject<List<Record>>(apiResponse);
public class Record
{
public string Key { get; set; }
public string Value { get; set; }
}
but I have this error:
deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TranslationsTools.Domain.Entities.Record]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Do you know how it should be done?
A couple of problems:
Your Record class in no way matches the JSON you've shown. The property names in your object need to match those found in the JSON. In this case that's a bit tricky due to the dots (.) in the JSON property names, but luckly Newtonsoft provides a workaround for that - by using its JsonProperty attribute to match the C# property to the JSON property, even though the names are different.
You need to deserialise to a single object, not a List.
You need:
public class Record
{
[JsonProperty("cart.empty.title")]
public string CartEmptyTitle { get; set; }
[JsonProperty("returns.confirmation.status.step1.next.arbitration")]
public string ReturnsConfirmationStatusStep1NextArbitration { get; set; }
[JsonProperty("returns.home_pickup.address.form.title")]
public string ReturnsHomePickupAddressFormTitle { get; set; }
}
and
var drupalRecord = JsonConvert.DeserializeObject<Record>(apiResponse);
Live demo: https://dotnetfiddle.net/LrNc04
(The creation of the Record class above was the result of pasting your JSON into https://json2csharp.com/ for automatic conversion.)
Your json string defines a dictionary, not a list. If you don't want to define a class, you can simply deserialize the string into a dictionary.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string jsontext = "{ \"cart.empty.title\":\"Il tuo carrello \u00e8 vuoto\", \"returns.confirmation.status.step1.next.arbitration\":\"A breve riceverai un\u0027email con le istruzioni su come effettuare il reso.\", \"returns.home_pickup.address.form.title\":\"Dove ritireremo i tuoi prodotti?\" }";
var record = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsontext);
foreach (var kvp in record) {
Console.WriteLine("{0} = {1}", kvp.Key, kvp.Value);
}
}
}
Demo here
You can access elements of the dictionary in the usual way:
Console.WriteLine(record["cart.empty.title"]); // prints Il tuo carrello รจ vuoto
However, I strongly recommend defining a class and using it like #ADyson suggests in their answer
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);
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);
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.