Deserialization using newtonsoft - c#

I'm new to C# and i want to deserialize the JSON file into the API using NewtonSoft but it lead me to this error
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'API.JSonConfiguration.exampleLibrary' 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.'"
string url = #"http://180.232.67.229/api/jfiller";
string Data = new WebClient().DownloadString(url
exampleLibrary json = JsonConvert.DeserializeObject<exampleLibrary>(Data);
MessageBox.Show(json.filler_id);
exampleLibrary Class:
public string filler_id { get; set; }
public string filler_title { get; set; }
public string filler_type { get; set; }
JSON
[
{
"filler_id":"1",
"filler_title":"Star118 E-CarDemo",
"filler_type":"1",
"filler_file":"Star118CarTeaser‌​1.mp4",
"filler_durat‌​ion":"83",
"created_a‌​t":"2017-06-10 09:08:41",
"updated":"2017-06-10 09:08:41","status":"0"
},
{
"filler_id":"2",
"filler_title":"Sta‌​r118",
"filler_type":‌​"2",
"filler_file":"S‌​tar118Solar1.PNG",
"f‌​iller_duration":"10"‌​,
"created_at":"2017-‌​06-10 09:09:26",
"updated":"2017-06-10 09:09:26","status":"0"
}
]

Try
JsonConvert.DeserializeObject<IEnumerable<exampleLibrary>>(Data);
You have an array of data but don't specify it in your JsonConvert or in your exampleLibrary Class(That I can see from your posted code).

Related

how to get Json values which are not in a class using C#?

I have the following problem:
I am a C# beginner and I want to create a weather app using the OpenWeatherApi.
The response of the api looks like this (it´s just an example):
[
{
"name": "London",
"lat": 51.5085,
"lon": -0.1257,
"country": "GB"
},
I want to get the lat and lon values.
My C# code looks like this:
public class CoordinatesResponse
{
public double Lat { get; set; }
public double Lon { get; set; }
}
private static string _coordinatesResponse;
static void ExtractCoordinatesFromJson()
{
CoordinatesResponse coordinatesresponse = JsonConvert.DeserializeObject<CoordinatesResponse>(_coordinatesResponse);
Console.WriteLine(coordinatesresponse.Lat);
Console.WriteLine(coordinatesresponse.Lon);
}
My error is the following:
Unhandled exception. Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WeatherApp.CoordinatesResponse' 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.
What do I wrong?
Your problem is in the type. Been an array, you must use List<CoordinatesResponse>:
static void ExtractCoordinatesFromJson()
{
var coordinatesresponses = JsonConvert.DeserializeObject<List<CoordinatesResponse>>(_coordinatesResponse);
foreach (var coordinatesresponse in coordinatesresponses)
{
Console.WriteLine(coordinatesresponse.Lat);
Console.WriteLine(coordinatesresponse.Lon);
}
}
To solve the issue " Cannot deserialize the current JSON array (e.g. [1,2,3])"
Follow the steps:
Go to any website that convert JSON to C# (e.g. https://json2csharp.com/).
Paste your JSON data in the JSON section and click on generate C# link button.
It will generate the object to deserialize the json array.
e.g. JsonDataService myData = JsonConvert.DeserializeObject(json);
The above object can be used to manipulate the JSON string object.

I am trying to deserialize a JSON into a list of objects using .NET 3.1

I have the following Json:
{
"Id":"2727",
"Region":"US",
"Data":[
{
"Title":"Director",
"JobDescription":"Coordinates the department activity",
"Department":"HR"
},
{
"Title":"Programmer",
"JobDescription":"Enterprise software developer",
"Department":"FR"
}
]
}
My format looks like this:
public class Data
{
public string Title { get; set; }
public string JobDescription { get; set; }
public string Department { get; set; }
}
public class Format
{
public string Id { get; set; }
public string Region { get; set; }
public List<Data> Data {get; set;}
}
I have tried to deserialize it like this:
var objects = JsonConvert.DeserializeObject<IEnumerable<Format>>(File.ReadAllText("mockJson.json")).ToList();
I am getting this exception:
An unhandled exception of type
'Newtonsoft.Json.JsonSerializationException' occurred in
Newtonsoft.Json.dll Cannot deserialize the current JSON object (e.g.
{"name":"value"}) into type
'System.Collections.Generic.IEnumerable`1[JSONParsingExample.Format]'
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 'GlobalOrgId', line 2,
position 15.
Just posting this as an answer because I think its worth making it more visible. I assumed the method call was going to have some issues with nesting lists inside a json, but I'm pleased to see it works.
Format format = JsonConvert.DeserializeObject<Format>(File.ReadAllText("mockJson.json"));
I inspected the elements and they all seem to be where they are supposed to be.
Just be careful because JsonConvert.DeserializeObject<T> returns an object of type T, not IEnumerable<T>.
When working with JSON in .NET I'd recommend moving over to the new built in stuff.
https://devblogs.microsoft.com/dotnet/net-core-image-processing/

Accessing JSON object from api in C# [duplicate]

This question already has answers here:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
(5 answers)
Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly
(6 answers)
Closed 2 years ago.
Im doing a Microsoft Cognitive Services project with langauge detection and text translation.
Im receiving Json from the Microsoft Api, and i want to access it as an object.
I've tried a few different things, including JsonConvert.DeserializeObject, and mapping it to my own objects. (Example below)
// Send the request and get response.
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
// Read response as a string.
if (response.ReasonPhrase == "OK")
{
//string result = await response.Content.ReadAsStringAsync();
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(result);
}
// The response:
[{
"detectedLanguage":
{
"language":"fi",
"score":1.0
},
"translations":
[
{"text":"This is a test, I hope it works. The text is in Finnish.","to":"en"},
{"text":"Dette er en test, jeg håber det virker. Teksten er på finsk.","to":"da"}
]
}]
// I found an online tool to generate the appropriate classes for mapping
public class DetectedLanguage
{
[JsonPropertyName("language")]
public string Language { get; set; }
[JsonPropertyName("score")]
public double Score { get; set; }
}
public class Translation
{
[JsonPropertyName("text")]
public string Text { get; set; }
[JsonPropertyName("to")]
public string To { get; set; }
}
public class MyArray
{
[JsonPropertyName("detectedLanguage")]
public DetectedLanguage DetectedLanguage { get; set; }
[JsonPropertyName("translations")]
public List<Translation> Translations { get; set; }
}
public class Root
{
[JsonPropertyName("MyArray")]
public List<MyArray> MyArray { get; set; }
}
// The Error im getting
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'textananlytics_test.Root' 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.'
You can change
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(result);
to
List<MyArray> list = JsonConvert.DeserializeObject<List<MyArray>>(result);
Root myDeserializedClass=new Root{MyArray=list};
In your case, JSON must has next structure:
{
"MyArray": [
{ /* MyArray jobject */ },
{ /* MyArray jobject */ },
...
]
}
So Yiyi You wrote correct processing

Json response to C# Object

I am trying to convert Json Response to C# object. My code is as below.
$ HttpResponseMessage response = client.GetAsync(TARGETURL).Result;
HttpContent content = response.Content;
// ... Check Status Code
Console.WriteLine("Response StatusCode: " + (int)response.StatusCode);
// ... Read the string.
string result = content.ReadAsStringAsync().Result;
Environment myJsonResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<Environment>(result);
Console.Write(myJsonResponse.id);
My Json Object Class is:
public class Environment
{
public string id { get; set; }
public string url { get; set; }
public string name { get; set; }
public string error { get; set; }
public int container_hosts_count { get; set; }
}
Result string is:
"[{\"id\":\"23745576\",\"url\":\"https://cloud.mycloud.com/configurations/23745576\",\"name\":\"mycloud Code Screen - Andy Pande\",\"error\":\"\",\"container_hosts_count\":0}]"
I am getting an error as:
Newtonsoft.Json.JsonSerializationException occurred
HResult=0x80131500
Message=Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Environment' 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.
As per the error, you are trying to deserialize a JSON array into a single object. Update your deserialization to:
var myJsonResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<Environment>>(result);

Converting json to objects in C#

I have data in the following format. I want to convert this data to objects.
Result = {
"Location": [
"bangalore",
1,
"chennai",
1,
"mumbai",
1,
"delhi",
0,
"Agra",
0
]
}
In my Location.cs i have the following fields. i want to assign the data to this fields. How can i achieve this
public string loc { get; set; }
public int count { get; set; }
I tried with
Location = Result.ToObject<List<Location>>();
but not working getting the following error
{"Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[Location]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo 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.\r\nPath 'Location'."}
Take a look at the native json deserializaton that is part of .NET
MSDN - How to: Serialize and Deserialize JSON Data
The problem is this: Result is a JSON object, not a JSON array, therefore you can't convert it to a List<Location>.
You would need a class that contains a list of locations and convert to that class:
public class LocationsContainer
{
public List<Location> Location { get; set; }
}
Result.ToObject<LocationsContainer>();
Try with Json.NET library.
List<Location> locations = JsonConvert.DeserializeObject<List<Location>>(result);

Categories

Resources