Error On Parsing JSONData - c#

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)

Related

Deserialize json into csharp object errors - Could not cast or convert from System.String to ProjectName.Models.CarsModel

I'm stuck with a tricky json.
trying to deserialize below web api json into c# object.
Seems like it has no key, only the below value.
["toyota","bmw","nissan","gmc","mazda","opel","international","honda","ford"]
Below is my code that is giving me error
var deserializedObject = JsonConvert.DeserializeObject<List<CarsModel>>(result);
public class CarsModel
{
[JsonPropertyName("MyJson")]
public List<string>? MyJson { get; set; }
}
'Error converting value "toyota" to type 'CarsModel'. Path '[0]', line 1, position 9.'
ArgumentException: Could not cast or convert from System.String to ProjectName.Models.CarsModel.
Please try the below code.
public class CarsModel
{
public CarsModel()
{
MyJson =new List<string>();
}
public List<string>? MyJson { get; set; }
}
var deserializedObject = JsonConvert.DeserializeObject<CarsModel>(result);

How to remove double quotes from a string inside JSON string?

I am getting JSON string request from the server side. That part not handling by my self. They send the request as following (policyJson)
{"Data":"[{\"NAME\":\"BOARD OF INVESTMENT OF SRI LANKA\",\"STARTDATE\":\"\\\/Date(1584210600000)\\\/\",\"ENDDATE\":\"\\\/Date(1615660200000)\\\/\",\"SCOPE\":\"As per the standard SLIC \\\"Medical Expenses\\\" Policy Wordings\",\"DEBITCODENO\":1274}]","ID":200}
Then I Deserialize using
BV_response _res_pol = JsonConvert.DeserializeObject<BV_response>(policyJson);
Class BV_response
public class BV_response
{
public int ID { get; set; }
public string Data { get; set; }
}
Then
string res = _res_pol.Data.Replace("\\", "");
var policyDetails = JsonConvert.DeserializeObject<PolicyData>(res);
Class PolicyData
public class PolicyData
{
public string NAME { get; set; }
public DateTime STARTDATE { get; set; }
public DateTime ENDDATE { get; set; }
public string SCOPE { get; set; }
public int DEBITCODENO { get; set; }
}
For this JSON string I am getting following exception in this line
var policyDetails = JsonConvert.DeserializeObject(res);
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'SHE_AppWS.Models.PolicyData' 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.
Path '', line 1, position 1.
This is valid JSON, and does not need string manipulation. It's just JSON stored within JSON.
Do not try unescaping JSON yourself. If the JSON is not valid, get it fixed at source.
Your problem is that you are deserializing the inner JSON to a single object, but it is an array.
Instead, deserialize to a List<> or array.
BV_response _res_pol = JsonConvert.DeserializeObject<BV_response>(policyJson);
var policyDetails = JsonConvert.DeserializeObject<List<PolicyData>>(_res_pol.Data);

Deserialize string into object array

I'm new to JSON Serialization and Deserialization, so I've been googling alot about this topic, but I couldn't come to figuring out my problem. My main goal is to deserialize the JSON string and write a SQL insert statement from it. Being new to this topic, I'm not sure what deserializing a JSON string returns, but I read somewhere that it returns an object array? For example how would I deserialize this JSON string:
[{"First_Name":"Bob","Last_Name":"Smith","Job":"Engineer"},
{"First_Name":"Jane","Last_Name":"Doe","Job":"Scientist"}]
and deserialize it into a SQL statement?
Using Json.Net
var users = JsonConvert.DeserializeObject<List<User>>(json);
Using JavaScriptSerializer
var users = new JavaScriptSerializer().Deserialize<List<User>>(json);
public class User
{
public string First_Name { get; set; }
public string Last_Name { get; set; }
public string Job { get; set; }
}

Deserialize string to list class in 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 );

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

Categories

Resources