Deserialize string to list class in c# - c#

my json string data is
string r= "{"data":
[
{"ForecastID":54239761,"StatusForecast":"Done"},
{"ForecastID":54240102,"StatusForecast":"Done"},
{"ForecastID":54240400,"StatusForecast":"Done"},
{"ForecastID":54240411,"StatusForecast":"Done"},
{"ForecastID":54240417,"StatusForecast":"Done"}
]
}"
and my json class is
public class Datum
{
public string ForecastID { get; set; }
public string StatusForecast { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
}
i run this code
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Datum> ListAnswers = serializer.Deserialize<List<Datum>>(r);
Console.WriteLine("\n Deserialize: \n" + ListAnswers.Count );
and have 0 count of ListAnswers.Count
but should be 5 pieces.
what wrong? how to properly deserialize json string?

You need to deserialize an instance of RootObject.. since it is the root of the data. What you're trying to do right now is deserialize the whole thing as a list.. which it isn't. Its a root object with a list underneath it:
RootObject obj = serializer.Deserialize<RootObject>(r);
foreach (var item in obj.data) {
Console.WriteLine("\n Deserialize: \n" + item.ForecastID);
}

It looks like your JSON string is an object, not an array. In order to parse JSON directly into List, the JSON should be an array.
So, in your example above, if you modified your JSON string to be
[
{"ForecastID":54239761,"StatusForecast":"Done"},
{"ForecastID":54240102,"StatusForecast":"Done"},
{"ForecastID":54240400,"StatusForecast":"Done"},
{"ForecastID":54240411,"StatusForecast":"Done"},
{"ForecastID":54240417,"StatusForecast":"Done"}
]
it would parse as you are expecting it to be.
Another option would be to create a secondary C# class to reflect the structure of the JSON. Something along these lines:
public class DataContainer
{
public List<Datum> Data {get;set;}
}
This provides the 'data' property that is contained within your JSON string, so the serializer would populate the Data property with the list of Datum objects. Your calling code would then look like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
DataContainer results = serializer.Deserialize<DataContainer>(r);
Console.WriteLine("\n Deserialize: \n" + results.Data.Count );

Related

Convert complex JSON to Generic List using Newtonsoft

Below is a Json :
[{
"Result": {
"description": "Application Security Supp Specialist",
"code": "40000003"
}
}, {
"Result": {
"description": "Gvt Cyber Intelligence Specialist",
"code": "40001416"
}
}, {
"Result": {
"description": "Gvt Record Retention Specialist",
"code": "40001428"
}
}]
And below is the class structure which i have created as i need to fill this into a C# object.
I am trying to create a collection of RulesEngineOutput and fill it with the json contents.
public class RulesEngineOutput
{
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
}
public class RulesEngineOutputCollection
{
public IEnumerable<RulesEngineOutput> ProbableRoles { get; set; }
}
I am trying to achieve this using below code :
var bodyJson = JsonConvert.SerializeObject(bodyString);
RulesEngineOutputCollection result = new RulesEngineOutputCollection();
foreach (var item in bodyJson)
{
result = JsonConvert.DeserializeObject<RulesEngineOutputCollection>(item.ToString());
}
But this is throwing exception as the item gets a char, what i am thinkiong is that i need to pass a JSON object in the loop but i am not able to get one.
Everytime i get is a JSON string.
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'RulesEngineOutputCollection' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo 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.
The problem is that you have an intermediary object between your RulesEngineOutput and your collection. You need to restructure your objects as such:
public class RulesEngineOutput
{
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
}
public class RulesEngineOutputResult
{
public RulesEngineOutput Result { get; set; }
}
public class RulesEngineOutputCollection
{
public IEnumerable<RulesEngineOutputResult> ProbableRoles { get; set; }
}
And then when you have this restructuring done, you can deserialize directly to your RulesEngineOutputCollection instead of to an object and iterating and deserializing again.
result = JsonConvert.DeserializeObject<RulesEngineOutputCollection>(bodyString);
Thanks a lot Max,Nathan and others. So finally i made some changes in code and below is the code which i changed tomake the things work :
var jToken = JObject.Parse(responseContent);
var bodyString = jToken.SelectToken("body");
var bodyJson = JsonConvert.SerializeObject(bodyString);
List<RulesEngineOutput> result = new List<RulesEngineOutput>();
try
{
foreach (var item in bodyString)
{
var formattedItem = item.SelectToken("Result");
var resultItem = JsonConvert.DeserializeObject<RulesEngineOutput>(formattedItem.ToString());
result.Add(resultItem);
}
}
Hope it helps others as well.
As Nathan Werry said, you have an object layered into another object and because of that, you cannot deserialize the data in the way you want it. However, you can work around that if you first create an array of these results and assign it later to your ProbableRoles property:
var rules = new RulesEngineOutputCollection
{
ProbableRoles = JsonConvert.DeserializeObject<Result[]>(bodyString).Select(r => r.Data).ToList()
};
public class Result
{
[JsonProperty("Result")]
public RulesEngineOutput Data { get; set; }
}
Everything else stays the same. You basically create a new list out of your array of results. I could also assign the Select() result directly (without calling .ToList()) but this ensures that the object actually has the data and not just a reference to an enumeration.

Json Deserealization error

I try to deserialize json and write to List
Here is my ViewModel code
public async void Posts_download()
{
string url = "https://www.reddit.com/top/.json?count=50";
var json = await FetchAsync(url);
var json_new = json.ToString();
List<RootObject> rootObjectData = JsonConvert.DeserializeObject<List<RootObject>>(json);
PostsList = new List<RootObject>(rootObjectData);
}
private async Task<string> FetchAsync(string url)
{
string jsonString;
using (var httpClient = new System.Net.Http.HttpClient())
{
var stream = await httpClient.GetStreamAsync(url);
StreamReader reader = new StreamReader(stream);
jsonString = reader.ReadToEnd();
}
return jsonString;
}
And here is json response
JSON
I Have this error
How I can handle it?
UPDATE
Here is clases that I generate from json responce
Classes
The json you posted isn't an array, its a json object, however you are asking jsonconvert to deserialize to an array. Change your RootObject class and add the other classes to:
class RootObject
{
string kind {get;set}
Data data {get;set;}
List<Child> {get;set;}
}
class Data
{
string modhash {get;set;}
string before {get;set;}
string after {get;set;}
}
class Child
{
string kind {get;set;}
data .. and so on.
}
Then you would change your jsonconver line to:
RootObject rootObjectData = JsonConvert.DeserializeObject<RootObject>(json);
Please note this isn't a fully working example because it would have been cumbersome to fully define the Child class as there are many properties.
The reason this is needed is because the json posted was a json object that held an array. You can tell becuase the json started with "{", if it was an array it would have started with a "["
That JSON doesn't return an array. The RootObject should look like this:
public class RootObject
{
public string kind { get; set; }
public Data data { get; set; }
}
Then call it without the List<>:
RootObject rootObjectData = JsonConvert.DeserializeObject<RootObject>(json);
In data there is a List<Child> children. I guess you were looking for that one. Please refer to Easiest way to parse JSON response to see how to create the C# objects.

SerializeObject c# object with Newtonsoft.Json

when I trying to serialize to json an regular class that i read before all the properties in the json starts with $.
Why and how can I resolve it
Your question does not have enough details, perhaps the below will help with going from a C# class to a JSON object and back.
First Create a class that mimics your JSON string (object) structure:
public class JSONobject
{
public Foo = new Foo();
}
public class Foo
{
public string First { get; set; }
public string Last {get;set;}
public int ID {get;set;}
........
........
public Bar = new Cover();
}
public class Bar
{
public int ID{ get;set; }
........
}
Then, initialize the object as well as the serializer:
JSONobject jsonOb = new JSONobject();
JavaScriptSerializer serializer = new JavaScriptSerializer();
Finally, parse the jsonString into your defined class:
try
{
jsonOb = serializer.Deserialize<JSONobject>(jsonString);
//ViewBag.jsondecoded = "Yes";
}
catch (Exception e)
{
//ViewBag.jsonDecoded = "No" + ", Exception: " + e.Message.ToString();
}
The object now has all the data from your JSON object.
At last, you can do this backwards, just serialize the object:
string json = JsonConvert.SerializeObject(jsonOb);

How can I deserialize JSON containing delimited JSON?

I have a problem with deserializing a Json-string to an object.
This is a sample json i receive from a webservice:
{
"GetDataResult":
"{
\"id\":1234,
\"cityname\":\"New York\",
\"temperature\":300,
}"
}
And I have a class CityData that looks like this
[JsonObject("GetDataResult")]
public class CityData
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("cityname")]
public string CityName { get; set; }
[JsonProperty("temperature")]
public int Temperature { get; set; }
}
I try to deserialize the json with a call of the method DeserializeObject
var cityData = JsonConvert.DeserializeObject<CityData>(response);
but the root element seems to make problems...
Do you guys know how I can fix it, so that I receive a CityData-object with the data filled in?
The json response contains an object that within itself contains a json string representing the data result.
You need to deserialize twice, once for the response and one more for the data result.
var response = JsonConvert.DeserializeObject<JObject>(responseStr);
var dataResult = (string)response["GetDataResult"];
var cityData = JsonConvert.DeserializeObject<CityData>(dataResult);

Error On Parsing JSONData

I have this Json Array
[{"Fname":"Axe","Lname":"Venture" },{"Fname":"dsa","Lname":"das"}]
I am Using JSON.net to deserialize the Json array. My Class is as below
public class Cifo
{
public string Fname { get; set; }
public string Lname { get; set; }
}
The json array will be store in a string namely JSONData , when there is only 1 Json Data such as {"Fname":"Axe","Lname":"Venture" } . my code will not return any error . but when I have more than 1 JSON array data like above . I will get an exception "Cannot deserialize JSON array into type 'myClassName+Cifo'."
I am using this code to deserialize JsonConvert.DeserializeObject<Cifo>(JSONData)
How can I parse all the json data and store into an object ?
Try to deserializa to a list
var list = JsonConvert.DeserializeObject<List<Cifo>>(JSONData)

Categories

Resources