This is my Json List of Objects array that I stringified and sent to my controller
"[{\"Id\":\"fieldone\",\"Name\":\"fieldtwo\"}]"
How can I deserialize it in my controller and turn it into a list of Objects again?
Currently this is what I have:
var RoleList = JsonConvert.DeserializeObject<SampleViewModel>(Input.RoleList);
and these are my ViewModels
public class UserAddRoleListViewModel
{
public String Id { get; set; }
public String Name { get; set; }
}
public class SampleViewModel
{
public List<UserAddRoleListViewModel> Test { get; set; }
}
At the moment when I run it, I get this error
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'App.Data.ViewModels.SampleViewModel' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
What should I do to convert this into a list of UserAddRoleListViewModels?
EDIT: Added Controller and Relevant ViewModel
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult VerifyRole(SaveUserNewRoleViewModel Input)
{
var RoleList = JsonConvert.DeserializeObject<SampleViewModel>(Input.RoleList);
return null;
}
public class SaveUserNewRoleViewModel
{
[Required]
public String RoleId { get; set; }
public String RoleName { get; set; }
public String RoleList { get; set; }
}
Based on the shown JSON array and the error message indicating that you are trying to convert an array to a single object, it looks like you were suppose to do
var RoleList = JsonConvert.DeserializeObject<List<UserAddRoleListViewModel>>(Input.RoleList);
in order to parser the JSON correctly into a List<>
To make the following working
var RoleList = JsonConvert.DeserializeObject<SampleViewModel>(Input.RoleList);
your json should be like below
"{ Test:[{\"Id\":\"fieldone\",\"Name\":\"fieldtwo\"}] }"
Otherwise, for correct result fro your json
"[{\"Id\":\"fieldone\",\"Name\":\"fieldtwo\"}]"
use below
var RoleList = JsonConvert.DeserializeObject<List<UserAddRoleListViewModel>>(Input.RoleList);
Related
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.
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.
Trying to deserialize an array of book objects from the GoogleBook API.
Models: https://pastebin.com/24S16hZc
Confirmed API respons: https://pastebin.com/2q0aFGnf
Booking Page:
public BookingPage()
{
this.InitializeComponent();
ResizeWindow();
UpdateListView();
}
private void UpdateListView()
{
UserList_List.Items.Clear();
foreach (HelperLibrary.UserObject L in App.GlobalUserList)
{
UserList_List.Items.Add($" { L.FirstName } { L.LastName }");
}
//Prepare task
Task<HelperLibrary.Models.GoogleBook.RootObject[] > GetBooksTask = HelperLibrary.Helpers.APIHelper.SearchBooks("Hacker");
GetBooksTask.Wait();
HelperLibrary.Models.GoogleBook.RootObject[] Books = GetBooksTask.Result;
foreach(HelperLibrary.Models.GoogleBook.RootObject P in Books)
{
BookList_list.Items.Add(P.volumeInfo.title);
}
}
API Helper task
public class APIHelper
{
private static string BaseURL = "https://www.googleapis.com/books/v1/volumes";
public static async Task<HelperLibrary.Models.GoogleBook.RootObject[] > SearchBooks(string term)
{
using (var WebClient = new HttpClient { BaseAddress = new Uri(BaseURL) })
{
var ResponseHandler = WebClient.GetAsync($"?q= { term } ");
if (ResponseHandler.Result.IsSuccessStatusCode)
{
string x = await ResponseHandler.Result.Content.ReadAsStringAsync();
Debug.WriteLine(x);
Models.GoogleBook.RootObject[] items = JsonConvert.DeserializeObject<Models.GoogleBook.RootObject[]>(await ResponseHandler.Result.Content.ReadAsStringAsync());
return items;
}
else
{
return null;
}
}
}
}
Full error:
JsonSerializationException: Cannot deserialize the current JSON object
(e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[HelperLibrary.Models.GoogleBook+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) 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 'kind', line 2, position 8.
I'm already trying to declare it to an array, not a List?
Been trough most other threads about this, can't seem to find a situation similar to mine.
You seem to have misunderstood what is the RootObject. What you have defined as such is actually the inner object inside your RootObject.
I suggest you do this;
1) Rename your RootObject to Item
public class Item
{
public string kind { get; set; }
public string id { get; set; }
public string etag { get; set; }
public string selfLink { get; set; }
public VolumeInfo volumeInfo { get; set; }
public LayerInfo layerInfo { get; set; }
public SaleInfo saleInfo { get; set; }
public AccessInfo accessInfo { get; set; }
}
2) Create a new RootObject
public class RootObject
{
public string kind { get; set; }
public int totalItems { get; set; }
public List<Item> items { get; set; }
}
Then your Deserialize should look like this;
Models.GoogleBook.RootObject root =
JsonConvert.DeserializeObject<Models.GoogleBook.RootObject>(await ResponseHandler.Result.Content.ReadAsStringAsync());
Checking the structure of the json, i think what you are trying to get is the item array of the json if i am not mistaken. What you can do is Try to create a parent class containing the array Root Object something like this:
Public class RootParent
{
public string kind {get; set;}
public int totalItems {get;set;}
public List<RootObject> items {get; set;}
}
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.
I am getting following JSON data
[{"id":"1","text":"System Admin","target":{"jQuery1710835279177001846":12},"checked":true,"state":"open"},
{"id":"2","text":"HRMS","target":{"jQuery1710835279177001846":34},"checked":false,"state":"open"},
{"id":"3","text":"SDBMS","target":{"jQuery1710835279177001846":42},"checked":false},
{"id":"8","text":"Admin","target":{"jQuery1710835279177001846":43},"checked":false},
{"id":"9","text":"My test Admin","target":{"jQuery1710835279177001846":44},"checked":false,"state":"open"},
{"id":"24","text":"ModuleName","target":{"jQuery1710835279177001846":46},"checked":false,"state":"open"}]
which try to parsed using Json.Net using strongly type
this are my property class
public class testclass
{
public string id { get; set; }
public string text { get; set; }
public string #checked { get; set; }
public string state { get; set; }
public target jQuery1710835279177001846 { get; set; }
}
public class testclass2
{
public List<testclass> testclass1 { get; set; }
}
public class target
{
public string jQuery1710835279177001846 { get; set; }
}
and here i am trying to access the data i am getting exception
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'QuexstERP.Web.UI.Areas.SysAdmin.Controllers.testclass' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
My controller code look like
public void Test(string Name, object modeldata)
{
var obj = JsonConvert.DeserializeObject<testclass>(Name);
}
Any idea how to solve this issue in C#
Your Json string looks to have serialized array object in it because it contains [ ]. It means you have a Json string which is formed after serialization of array object. So you need to deserialized into array object, so try this
var obj = JsonConvert.DeserializeObject<List<testclass>>(jsonString);
you have Array of TestClass. so it should be like this.
var model= JsonConvert.DeserializeObject<List<testclass>>(Name);
why you are using JSonConvert ? in MVC3 you can do like this
return Json(yourmodel,JsonRequestBehavior.AllowGet);
Your json objects are like this
{
"id":"1",
"text":"System Admin",
"target":{
"jQuery1710835279177001846":12
},
"checked":true,
"state":"open"
}
It should be like this I guess
{
"id":"1",
"text":"System Admin",
"jQuery1710835279177001846":12,
"checked":true,
"state":"open"
}