JsonSerializationException in Json Deserializing using Json.NET - c#

I have a Json like this :
[{"id":"54718","title":"Khaleda to visit China","corres":"Special Correspondent","details":"DHAKA: On a 7-day visit, opposition BNP Chairperson Khaleda Zia will leave Dhaka for China on October 14.","photo":"2012October\/SM\/Khaleda-new-sm20121003132805.jpg"}]
To parse this Json , so far I have done :
public class Attributes
{
[JsonProperty("id")]
public string ID{ get; set; }
[JsonProperty("title")]
public string TITLE { get; set; }
[JsonProperty("corres")]
public string CORRES { get; set; }
[JsonProperty("details")]
public string DETAIL { get; set; }
[JsonProperty("photo")]
public string LINK { get; set; }
}
public class DataJsonAttributeContainer
{
public List<Attributes> NewsList{ get; set; }
//public Attributes attributes { get; set; }
}
public static T DeserializeFromJson<T>(string json)
{ //I'm getting the error here
T deserializedProduct = JsonConvert.DeserializeObject<T>(json);
return deserializedProduct;
}
& In my code :
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//parse data
var container = DeserializeFromJson<DataJsonAttributeContainer>(e.Result);
//load into list
for (i = 0; i < container.NewsList.Count ; i++)
{
newData[i] = new data();
newData[i].id = container.NewsList[i].ID;
newData[i].title = container.NewsList[i].TITLE;
newData[i].price = container.NewsList[i].CORRES;
newData[i].image = container.NewsList[i].DETAIL;
newData[i].link = container.NewsList[i].LINK;
}
The Problem is : container is getting the json from web server which I can see at debugger , but it's shoeing an exception while deserializing . Can anybody help please ?
The Exception I'm getting :
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'BanglaNewsPivot.MainPage+DataJsonAttributeContainer' 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.

Your json is an array (not a single object containing array). Calling your DeserializeFromJson as below
var attrs = DeserializeFromJson<List<Attributes>>(e.Result);
is enough.
--EDIT--
foreach (var attr in attrs)
{
Console.WriteLine("{0} {1}", attr.ID, attr.TITLE);
}

Related

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

C# Web Api - NUnit Testing - Newtonsoft.Json.JsonSerializationException

I need to deserialize the following JSON string.
{"status":"success","data":[{"id":4,"domainTitle":"Java","isDeleted":true},{"id":5,"domainTitle":"PHP","isDeleted":true},{"id":6,"domainTitle":"Angular","isDeleted":true}]}
The test code for the same is:
[Test]
public async Task TestGetDeletedDomainsAsync_UserDomains_StatusCodeOK()
{
using (var adminController = new AdminController(_adminService.Object))
{
//act
var response = _adminController.GetDeletedDomainsAsync();
var successStatus = await response.Content.ReadAsAsync<SuccessStatus>();
var returnData = JsonConvert.DeserializeObject<List<Domain>>(successStatus.Data.ToString());
// assert
Assert.Multiple(() =>
{
Assert.That(response, Is.TypeOf<HttpResponseMessage>());
Assert.That(returnData, Is.TypeOf<List<Domain>>());
Assert.AreEqual(response.StatusCode, HttpStatusCode.OK);
Assert.IsNotNull(successStatus);
Assert.AreEqual("success", successStatus.Status);
Assert.IsNotNull(returnData);
//checking if same object goes to service and also if that service is called once
_adminService.Verify(s => s.GetDeletedDomains(), Times.Once);
});
}
}
But when I try using the de-serializer, it gives an exception.
Newtonsoft.Json.JsonSerializationException : Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[IMS_NL.Models.Domain]' 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.
The line that displays the above error is --
var returnData = JsonConvert.DeserializeObject<List<Domain>>(successStatus.Data.ToString());
Help me with a solution. Thanks in advance.
You need to make a class which correspond your JSON string
public class Answer
{
public string Status { get; set; }
public List<Domain> Data { get; set; }
}
public class Domain
{
public int Id { get; set; }
public string DomainTitle { get; set; }
public bool IsDeleted { get; set; }
}
Then use
var returnData = JsonConvert.DeserializeObject<Answer>(successStatus.Data.ToString());
I think that your problem resides in the declaration of Domain class. You should define the below classes, according to the JSON you have posted:
public class Domain
{
public int id { get; set; }
public string domainTitle { get; set; }
public bool isDeleted { get; set; }
}
public class Result
{
public string status { get; set; }
public List<Domain> data { get; set; }
}
var returnData = JsonConvert.DeserializeObject<Result>(...);
You should replace the ... with the JSON you get from that you call.
Optionally, you could rename the above classes as you think that would be more suitable.

What is the best way to Deserialize an object from json to a class?

I am implementing a system for GPS Tracking, through the consumption of a web service api.
ERROR :
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'TrackingRequest.Devices' 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.
This is in a web form application in c# with HttpClient using json of Newtonsoft.
My code
using (HttpClient clientKey = new HttpClient())
{
clientKey.BaseAddress = new Uri("http://api.trackingdiary.com/");
clientKey.DefaultRequestHeaders.Add("Hive-Session", key);
clientKey.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage responseKey = clientKey.GetAsync("/v2/geo/devices/list").Result;
using (HttpContent contentkey = responseKey.Content)
{
Task<string> resultKey = contentkey.ReadAsStringAsync();
Devices obj = JsonConvert.DeserializeObject<Devices>(resultKey.Result);
Console.WriteLine();
}
}
My Class:
class position
{
[JsonProperty("lat")]
public int lat { get; set; }
[JsonProperty("lng")]
public int lng { get; set; }
[JsonProperty("hdop")]
public int hdop { get; set; }
[JsonProperty("fix")]
public bool fix { get; set; }
}
class Devices
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("date_contacted")]
public string date_contacted { get; set; }
[JsonProperty("startup")]
public string startup { get; set; }
[JsonProperty("position")]
public position position { get; set; }
}
}
I want in objects to perform in DataTable.
JSON EXAMPLE
JSON EXAMPLE
It looks like your JSON string contains an array of objects of the type in question. You are trying to deserialize it into a single instance, hence the error.
Try this:
IEnumerable<Devices> devices = JsonConvert.DeserializeObject<IEnumerable<Devices>>(resultKey.Result);
And please rename the class to singular since it appears to represent a single Device.

define string structure for deserialize json object nested

this is the json file:
{
"Message": {
"Code": 200,
"Message": "request success"
},
"Data": {
"USD": {
"Jual": "13780",
"Beli": "13760"
}
},
"LastUpdate": "2015-11-27 22:00:11",
"ProcessingTime": 0.0794281959534
}
I have a problem when I am converting to class like this:
public class Message
{
public int Code { get; set; }
public string Message { get; set; }
}
public class USD
{
public string Jual { get; set; }
public string Beli { get; set; }
}
public class Data
{
public USD USD { get; set; }
}
public class RootObject
{
public Message Message { get; set; }
public Data Data { get; set; }
public string LastUpdate { get; set; }
public double ProcessingTime { get; set; }
}
and when I deserialized with this code :
private void button1_Click(object sender, EventArgs e)
{
WebClient wc = new WebClient();
var json = wc.DownloadString(textBox1.Text);
List<User> users = JsonConvert.DeserializeObject<List<User>>(json);
dataGridView1.DataSource = json;
}
When I run the code I get an unhandled exception which says:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WindowsFormApp.EmployeeInfo+Areas]' 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.”
Can anyone tell me what I am doing wrong and how to get the last item deserialized correctly?
JSON.Net is expecting (when you pass a collection type to the DeserializeObject method), that the root object is an array. According to your data, it's an object and needs to be processed as a singular user.
And then you need to pass that to the dataSource, so you'd then wrap the deserialized User into var userList = new List<User>{user};
The error message is pretty straightforward. You are trying to deserialize something that isn't an array (your JSON string) into a collection (List<User>). It's not a collection so you can't do that. You should be doing something like JsonConvert.DeserializeObject<RootObject>(json) to get a single object.

Parse string to object

I get this string on my controller:
"[{\"id\":12},{\"id\":2,\"children\":[{\"id\":3},{\"id\":4}]}]"
I want to parse this, and create one foreach inside other foreach to get the parents and children.
I've been trying this:
var object = JsonConvert.DeserializeObject<MenuJson>(json);
where MenuJson is:
public class MenuJson
{
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("children")]
public List<string> children { get; set; }
}
I got this erro:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'AIO.Controllers.AdminMenuController+MenuJson' 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.
And I tried other approach:
var objects = JsonConvert.DeserializeObject<JObject>(json);
foreach (var property in objects)
{
var id = property.Value;
foreach (var innerProperty in ((JObject)property.Value).Properties())
{
var child = property.Value;
}
}
Both I got errors when I try to convert the string.
My question is, How can I make this working?
And for my string, which approach is the best for my needs?
Have you tried this?
public class MenuJson
{
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("children")]
public List<MenuJson> children { get; set; }
}
var list = JsonConvert.DeserializeObject<List<MenuJson>>(json);
Here's an working example:
public void Test()
{
string json = "[{\"id\":12},{\"id\":2,\"children\":[{\"id\":3},{\"id\":4}]}]";
var objects = JsonConvert.DeserializeObject<List<MenuJson>>(json);
foreach (var property in objects)
{
var id = property.id;
foreach (var child in property.children)
{
//child
}
}
}

Categories

Resources