Deserialize JSON in c# - what is wrong? - c#

I'm trying without success to deserialize this JSON in c#:
{
"settings": {
"path": "http:\/\/www.igormasin.it\/fileuploads\/tanja_23a6id"
},
"files": [{
"file": "\/IMG_0992-Edit_a.jpg"
}, {
"file": "\/IMG_1024-Edit_a.jpg"
}, {
"file": "\/IMG_1074-Edit_a.jpg"
}, {
"file": "\/Untitled-1.jpg"
}]
}
my code:
public class JsonTxt
{
public IList<string> settings { get; set; }
public IList<string> files { get; set; }
}
downloadstring contains the Json text:
var deserialized = JsonConvert.DeserializeObject<JsonTxt>(downloadString);
Console.WriteLine("*************************************************");
Console.WriteLine(deserialized.settings[0].ToString());
Console.WriteLine(deserialized.files.Count);
exception:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g.
{"name":"value"}) into type 'System.Collections.Generic.IList`1[System.String]' 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.
Path 'settings.path', line 1, position 20.'
I am not able to understand the error, and what I am suposed to do.. From what I understand IList is wrong, but what else would be the correct thing to write?

Your class structure needs to be something like this:
public class JsonTxt
{
public Settings Settings { get; set; }
public IList<File> Files { get; set; }
}
public class Settings
{
public string Path { get; set; }
}
public class File
{
public string File { get; set; }
}
Settings is an object, not a collection, and Files is a collection of objects not strings.

Your class type expect IList settings :
public class JsonTxt
{
public IList<string> settings { get; set; }
public IList<string> files { get; set; }
}
but in the json you provide is an object
"settings": {
"path": "http:\/\/www.igormasin.it\/fileuploads\/tanja_23a6id"
},
you should change JsonText attributes type to match with your JSON

Related

deserialize json into my C# object gives error

I get such JSON and want to deserialize it into my C# object. But this ends up in an error that cannot deserialize. Can I get help in fixing this?
public class UserDto {
public string Id { get; set; }
public string Name { get; set; }
public List<string> Permissions { get; set; }
}
Above is the model object for binding the API output
HttpResponseMessage response = await client.GetAsync($"/users");
if (!response.IsSuccessStatusCode || response.Content == null) {
return null;
}
string result = await response.Content.ReadAsStringAsync();
UserDto users = await response.Content.ReadAsJsonAsync<UserDto>();
List<UserDto> x2 = JsonConvert.DeserializeObject<List<UserDto>>(result);
The above getasync method gives me the below result and i am trying to deserialize it to object.
{
"users": [{
"id": "1",
"name": "ttest",
"permissions": [
"add",
"edit",
"delete"
]
}]
}
Error:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.List`1[****.Models.UserDto]'
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.
I get such JSON and want to deserialize it into my C# object. But this ends up in an error that cannot deserialize. Can I get help in fixing this?
In your JSON, Users JArray is inside a JObject, so to convert your JSON string you need List<User> inside a RootObject class like,
public class User
{
public string id { get; set; }
public string name { get; set; }
public List<string> permissions { get; set; }
}
public class Root
{
public List<User> users { get; set; }
}
Deserialize like,
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(result);
.NETFIDDLE

Deserializing a serialized JSON file

I have a JSON file that has been serialized through an API, in which I need to deserialize it to use the data it generated in my code. The issue is that I'm getting an Exception Unhandled error in which I have tried to understand the solution to the error, but I have had a few days off tunnel vision with this issue.
I have tried my best to link my issue with other threads, but have been lost for a few days. I did get some form of sprint finish with setting up a {get { return } } with a property but due to the setup of the code when serializing I couldn't do that. Instead I've tried to put the file outputted in a simple location and tried desalinizing it based on the file location.
ImageModeration image1 = JsonConvert.DeserializeObject<ImageModeration>(File.ReadAllText(#"C:\ModerationOutput.json"));
// deserialize JSON directly from a file
using (StreamReader file = File.OpenText(#"C:\ModerationOutput.json"))
{
JsonSerializer serializer = new JsonSerializer();
ImageModeration image2 = (ImageModeration)serializer.Deserialize(file, typeof(ImageModeration));
}
Here is my json file
[
{
"ImageUrl": "URL",
"ImageModeration": {
"CacheID": "396a972f-79ae-4b31-a54c-0ba3314318fa_637026883058218816",
"Result": false,
"TrackingId": "UKS_ibiza_464a60be-f57d-4ee1-aa37-13d04f151fdd_ContentModerator.F0_4ae15371-36c9-4cb2-8e21-83381a29432c",
"AdultClassificationScore": 0.0048455675132572651,
"IsImageAdultClassified": false,
"RacyClassificationScore": 0.011258091777563095,
"IsImageRacyClassified": false,
"AdvancedInfo": [
{
"Key": "ImageDownloadTimeInMs",
"Value": "37"
},
{
"Key": "ImageSizeInBytes",
"Value": "34854"
}
],
"Status": {
"Code": 3000,
"Description": "OK",
"Exception": null
}
},
"TextDetection": null,
"FaceDetection": null
}
]
This error comes from the first line of code.
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the
current JSON array (e.g. [1,2,3]) into type
'convertingJSON.Program+ImageModeration' 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.'
Specific to your JSON string that you have posted, you can refer to the following code snippet to deserialize your string into its respective components.I am using the Newtonsoft JSON library which is a popular high-performance JSON framework for .NET. A working example can be found at: https://dotnetfiddle.net/RmXNHM
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string json=#"[{'ImageUrl':'URL','ImageModeration':{'CacheID':'396a972f-79ae-4b31-a54c-0ba3314318fa_637026883058218816','Result':false,'TrackingId':'UKS_ibiza_464a60be-f57d-4ee1-aa37-13d04f151fdd_ContentModerator.F0_4ae15371-36c9-4cb2-8e21-83381a29432c','AdultClassificationScore':0.004845567513257265,'IsImageAdultClassified':false,'RacyClassificationScore':0.011258091777563095,'IsImageRacyClassified':false,'AdvancedInfo':[{'Key':'ImageDownloadTimeInMs','Value':'37'},{'Key':'ImageSizeInBytes','Value':'34854'}],'Status':{'Code':3000,'Description':'OK','Exception':null}},'TextDetection':null,'FaceDetection':null}]";
var Sresponse = JsonConvert.DeserializeObject<List<RootObject>>(json);
foreach(var value1 in Sresponse)
{
Console.WriteLine(value1.ImageUrl);
Console.WriteLine(value1.ImageModeration.CacheID);
}
}
}
public class AdvancedInfo
{
public string Key { get; set; }
public string Value { get; set; }
}
public class Status
{
public int Code { get; set; }
public string Description { get; set; }
public object Exception { get; set; }
}
public class ImageModeration
{
public string CacheID { get; set; }
public bool Result { get; set; }
public string TrackingId { get; set; }
public double AdultClassificationScore { get; set; }
public bool IsImageAdultClassified { get; set; }
public double RacyClassificationScore { get; set; }
public bool IsImageRacyClassified { get; set; }
public List<AdvancedInfo> AdvancedInfo { get; set; }
public Status Status { get; set; }
}
public class RootObject
{
public string ImageUrl { get; set; }
public ImageModeration ImageModeration { get; set; }
public object TextDetection { get; set; }
public object FaceDetection { get; set; }
}
Output:
URL
396a972f-79ae-4b31-a54c-0ba3314318fa_637026883058218816
Use this site to convert you're JSON to a C# object and then deserialize to it.
According to the error it seems you may have been missing a property i.e. the object does not correspond to the JSON

.net core API sending array object

I have student class with array StudentPhones. When i remove StudentPhones property from Student class is working perfectly when post with Postman. But when add StudentPhones property then Postman gives me this error:
{
"StudentPhones": [
"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'DataAccess.StudentPhone' 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. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\r\nPath 'StudentPhones', line 4, position 23."
]
}
public class Student
{
public string StudentName { get; set; }
public string StudentSurname { get; set; }
public StudentPhone StudentPhones { get; set; }
}
public class StudentPhone
{
public int PhoneType{ get; set; }
public string PhoneNumber { get; set; }
}
public async Task<ServiceResult> SaveStudent([FromBody]Student student)
{
}
How can I post this json? (I am using angular 6 in real, postman is only for example.)
my json
{
"studentName": "test",
"studentSurname": "test",
"studentPhones": [
{
"phoneType": 1,
"phoneNumber ": "111111111"
},
{
"phoneType": 2,
"phoneNumber ": "2222222222"
}
],
}
You have an array of phones in your JSON, so instead of public StudentPhone StudentPhones { get; set; } in your model, you should have public List<StudentPhone> StudentPhones { get; set; }

Using JSON.net to deserialize a list of nested objects

Thanks in advance for your help.
I have a JSON file that contains a list of nested objects. Using the code below - I get an exception on the call to DeserializeObject. We are using JSON.net
Any help is appreciated
JSON:
[
{
"Email": "james#example.com",
"Active": true,
"CreatedDate": "2013-01-20T00:00:00Z",
"Input": {
"User": "Jim",
"Admin": "John"
},
"Output": {
"Version": "12345",
"Nylon": "None"
}
},
{
"Email": "bob#example.com",
"Active": true,
"CreatedDate": "2013-01-21T00:00:00Z",
"Input": {
"User": "Bob",
"Admin": "John"
},
"Output": {
"Version": "12399",
"Nylon": "134"
}
}
]
To support the deserialization I have created the following class structure.
public class Test002
{
public class Input
{
public string User { get; set; }
public string Admin { get; set; }
}
public class Output
{
public string Version { get; set; }
public string Nylon { get; set; }
}
public class RootObject
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public Input input { get; set; }
public Output output { get; set; }
}
public class TestCases
{
public List<RootObject> rootObjects { get; set; }
}
}
And finally here is the call to JSON.net JsonConvert.DeserializeObject - throws the following exception.
Test002.TestCases tTestCases = JsonConvert.DeserializeObject<Test002.TestCases>(File.ReadAllText(#"C:\test\Automation\API\Test002.json"));
I think I need something like this - to deseralize the list of objects - The code below fails
Test002.TestCases tTestCases = JsonConvert.DeserializeObject<IList<Test002.TestCases>>(File.ReadAllText(#"C:\test\Automation\API\Test002.json"));
Exception:
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code
Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'APISolution.Test002+TestCases' 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.
Why don't change TestCases to be a list? Works perfectly.
public class TestCases : List<RootObject> {}
The issue here is that you're trying to deserialize into an IList. IList is an interface, not a concrete type so JSON.NET doesn't know what to create. You need to tell it the exact type you want:
List<Test002.TestCases> tTestCases = JsonConvert.DeserializeObject<List<Test002.TestCases>>(File.ReadAllText(#"C:\test\Automation\API\Test002.json"));
You could cast that into an IList like this:
IList<Test002.TestCases> tTestCases = JsonConvert.DeserializeObject<List<Test002.TestCases>>(File.ReadAllText(#"C:\test\Automation\API\Test002.json"));
Perhaps try something as simple as this:
var tTestCases = JsonConvert.DeserializeObject<Test002.RootObject[]>(File.ReadAllText(#"C:\test\Automation\API\Test002.json"));
According to the json-data specified, you got some IEnumerable of RootObjects.
Your classes are well-composed, except the Test002 class. Everything should be OK if you try to deserialize json-data as List. Try something like
var result = JsonConvert.DeserializeObject<List<RootObject>>(File.ReadAllText(#"C:\test\Automation\API\Test002.json"));
If you strongly need the instance of your Test002 class, you should use
Test002.TestCases result = new TestCases(){
rootObjects = JsonConvert.DeserializeObject<List<RootObject>(File.ReadAllText(#"C:\test\Automation\API\Test002.json"))
};

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.

Categories

Resources