Console App Failing to Deserialize the JSON - c#

I'm receiving the following error when executing my code:
JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type
'AzureWinWorkloadList.AzureWinWorkloadList+Data[]' 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 'SkipToken', line 2, position
14.
This is a standalone console app not part of a MVC type project. Also, this had previously worked for me a few weeks back but when I went back to it, now I get that error.
Here is what my JSON looks like:
{
"SkipToken": null,
"Data": [
{
"name": "5678-PLACE-32",
"OSType": "Windows",
"CompName": "COMPUTER001",
"RGName": "RG1234",
"SubID": "AA1234567891011",
"SubName": "SUBNAME-Tool"
},
{
"name": "5678-PLACE-33",
"OSType": "Windows",
"CompName": "SERVER001",
"RGName": "RG1234",
"SubID": "AB1234567891011",
"SubName": "SUBNAME-Tool"
},
{
"name": "5678-PLACE-34",
"OSType": "Windows",
"CompName": "COMPUTER002",
"RGName": "RG1234",
"SubID": "AC1234567891011",
"SubName": "SUBNAME-Tool"
},
{
"name": "5678-PLACE-35",
"OSType": "Windows",
"CompName": "SERVER002",
"RGName": "RG1234",
"SubID": "AD1234567891011",
"SubName": "SUBNAME-Tool"
}
]
}
Here's my model Class:
public class Data
{
public string Name { get; set; }
public string OSType { get; set; }
public string CompName { get; set; }
public string RGName { get; set; }
public string SubID { get; set; }
public string SubName { get; set; }
}
Here is my Code:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AzureWinWorkloadList
{
class AzureWinWorkloadList
{
static void Main(string[] args)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://samm-prod-azfun.azurewebsites.net/api/...");
var responseTask = client.GetAsync("");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<Data[]>();
readTask.Wait();
var compnames = readTask.Result;
foreach (var CompName in compnames)
{
Console.WriteLine(CompName.CompName);
}
}
}
Console.ReadLine();
}
This is the line where the error occurs
readTask.Wait();
Any guidance on this would be appreciated!
Thanks in advance!

You need a wrapper class to deserialize the JSON data.
public class WrapperClass
{
public SkipTokenClass SkipToken { get; set; }
public IEnumerable<Data> Data { get; set; }
}
...
var readTask = result.Content.ReadAsAsync<WrapperClass>();
...
var wrapper = readTask.Result;
Use wrapper.Data to access the data.
Btw, aware that the property Name in Data class is different from the property name in the JSON data, consider use JsonPropertyAttribute.
[JsonProperty("name")]
public string Name { get; set; }

Related

Issue in Deserializing JSON Response Data to List

i having issues getting the elements in data into a list.
I want to be able to get User_ID, Country, Continent and other elements to a list after which i will do a bulk insert to the database.
The Error i get
Error Message
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in mscorlib.dll but was not handled in user code
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Country_API.Response]' 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.
This is the JSon Data returned from the API
{
"Status": "200 Ok",
"Message": "Data retrieved",
"Response": {
"current_page": 1,
"data": [
{
"User-ID": "EAD001",
"Country": "Ghana",
"Continent": "Africa",
"Gender": "Male",
"Email": "ead1#yahoo.com",
"Religion": ""
},
{
"User-ID": "EAD002",
"Country": "Senegal",
"Continent": "Africa",
"Gender": "Female",
"Email": "ead2#yahoo.com",
"Religion": "Muslim"
}
]
}
}
I am trying to Deserilize but it throws the above error.. this is what i am trying
if (result.IsSuccessStatusCode)
{
string toJsonString = await result.Content.ReadAsStringAsync();
var deserialize = JsonConvert.DeserializeObject<List<Response>>(toJsonString);
}
Json Model
public class Data
{
public string User-ID { get; set; }
public string Country { get; set; }
public string Continent { get; set; }
public string Gender { get; set; }
public string Email { get; set; }
public string Religion { get; set; }
}
public class Response
{
public int current_page { get; set; }
public IList<Data> data { get; set; }
}
public class Application
{
public string Status { get; set; }
public string Message { get; set; }
public Response Response { get; set; }
}
How to i achieve this please?
You're trying to deserialize the List inside the object. You need to deserialize the entire object. Try this:
if (result.IsSuccessStatusCode)
{
string toJsonString = await result.Content.ReadAsStringAsync();
var deserialize = JsonConvert.DeserializeObject<Application>(toJsonString);
IList<Data> dataList = deserialize.Response.data;
}
Issue is here . You have used "List" instead of "Response". bcoz in JSON "Response" is object not a list
var deserialize = JsonConvert.DeserializeObject<List<Response>>(toJsonString);
use like this.
var deserialize = JsonConvert.DeserializeObject<Response>(toJsonString);

How to Deserialize a JSON Array from Web API in UPW C#?

I want to connect to bitbay web api, get data JSON from there and save it to a file. My JSON looks like that:
{
"status": "Ok",
"items": [
{
"id": "737a2935-84c9-11ea-8cdc-0242ac11000e",
"t": "1587581134890",
"a": "0.00926098",
"r": "29999",
"ty": "Buy"
},
{
"id": "6c4474fa-84c9-11ea-8cdc-0242ac11000e",
"t": "1587581122794",
"a": "0.02475367",
"r": "29999",
"ty": "Buy"
}
]
}
I want to get t,a,r and ty from it. I've got code:
public class TradeModel
{
public decimal R { get; set; }
public decimal A { get; set; }
public string Ty { get; set; }
public DateTime T { get; set; }
}
public class TradeItemModel
{
public TradeModel Items { get; set; }
}
public class TradeProcessor
{
public static async Task<TradeModel> LoadTrades( int limit = 1 )
{
string url = "";
if (limit <= 300)
{
url = $"https://api.bitbay.net/rest/trading/transactions/BTC-PLN?limit={ limit }";
}
else
{
}
using (HttpResponseMessage response = await ApiHelper.ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
TradeItemModel trade = await response.Content.ReadAsAsync<TradeItemModel>();
return trade.Items;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
After I run this code I gets an Exception:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'DemoLibrary.TradeModel' 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 'items', line 1, position 24.”
The Item in TradeItemModel class should be a collection TradeModel[] or List<TradeModel>, and you can also add Status to check it if is OK or KO:
public class TradeItemModel
{
public string Status { get; set; }
public List<TradeModel> Items { get; set; }
}
You must change also the method signature to:
public static async Task<List<TradeModel>> LoadTrades( int limit = 1 )
I hope this helps you out.

Json formatting error message when making GET HTTP Call

i'm trying to return a list of users from our software and format the names and email addresses of these users into a list so can compare this to other lists and determine what is more accurate. i'm making the request using the code below.
Question: How do I format my code to accept a json array as the error message states?
public void MakeCall()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(_urlParameters).Result;
if (response.IsSuccessStatusCode)
{
var dataObjects = response.Content.ReadAsAsync<IEnumerable<WorkfrontDataObjects>>().Result;
foreach (var workfrontData in dataObjects)
{
Console.WriteLine("{0}", workfrontData.Email);
}
}
Console.ReadLine();
}
public class WorkfrontDataObjects
{
public string[] Email { get; set; }
public string[] Name { get; set; }
public WorkfrontDataObjects()
{
}
}
Error Message:
JsonSerializationException: Cannot deserialize the current JSON object
(e.g. {"name":"value"}) into type
'System.Collections.Generic.IEnumerable`1[ManageWorkfrontADUserDistros.WorkfrontDataObjects]'
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 'data', line 1, position 8.
UPDATE, adding json:
{
"data": [
{
"ID": "000000000000000000000000000000",
"name": "name",
"objCode": "USER",
"emailAddr": "email"
},
{
"ID": "000000000000000000000000000000",
"name": "name",
"objCode": "USER",
"emailAddr": "email"
},
2500 of whats above with obviously real data
Given your JSON, your model needs to look like this:
public class RootObject
{
[JsonProperty("data")]
public List<Item> Data { get; set; }
}
public class Item
{
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("objCode")]
public string ObjCode { get; set; }
[JsonProperty("emailAddr")]
public string Email { get; set; }
}
You can rename the classes and properties to suit your needs without affecting the deserialization, as long as the names in the [JsonProperty] attributes match the JSON.
Then you should be able to receive the data like this:
if (response.IsSuccessStatusCode)
{
var rootObject = response.Content.ReadAsAsync<RootObject>().Result;
foreach (var item in rootObject.Data)
{
Console.WriteLine(item.Email);
}
}
Your string[] should be string in WorkfrontDataObjects and email should be emailAddr

Can't deserialize JSON into C# POCO

I can't convert JSON Object into C# class object I've tried many things but the same error pops up:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type
'System.Collections.Generic.List`1[CoderwallDotNet.Api.Models.Account]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly.
I am using this JSON and tring to get the response in windows 8.1 application.
[
{
"id": 1,
"time": 40,
"srcLong": 35.909124,
"srcLat": 31.973628,
"destLong": 35.898258,
"destLat": 31.985622,
"subSites": [
{
"id": 1,
"name": "location1"
},
{
"id": 2,
"name": "location2"
},
{
"id": 3,
"name": "locaion3"
}
]
}]
and the I tried to read from the JSON using webclient but its not working it can't recognize it so I am using Newtonsoft.Json and I creted these class to get the response.
public class SubSite
{
public int id { get; set; }
public string name { get; set; }
}
public class RootObject
{
public int id { get; set; }
public int time { get; set; }
public double srcLong { get; set; }
public double srcLat { get; set; }
public double destLong { get; set; }
public double destLat { get; set; }
public List<SubSite> subSites { get; set; }
}
var serviceUri = "http://localhost:24728/api/sites";
var client = new HttpClient();
var response = await client.GetAsync(serviceUri);
var datafile = await response.Content.ReadAsStringAsyn();
List<RootObject> data = JsonConvert.DeserializeObject<List<RootObject>>(datafile);
test1234.Text = data.ToString();//i am trying to for eample destlat
but I can't get the value I am getting the response and everything is fine but idk how to put it into object and use it where ever I want. For example, I want to get the value of time and the other but I have problem with List of subsites or get the location inside the subsites or srclong or srclat and here is the project how to get the Json to c# object:
https://onedrive.live.com/?cid=e648f5a0f179f346&id=E648F5A0F179F346%218429&ithint=folder,rar&authkey=!ALKlJdwsb8ER2FA
This works fine:
var data = JsonConvert.DeserializeObject<RootObject>(datafile)
You can deserialize into a dynamic object if you are not too particular about losing intellisense. One advantage to using a dynamic is that you don't have to create classes just to be able to deserialize and also that you don't need to update your class structures if the returned data has changed. As an example you can do this:
dynamic jsonValue = JsonConvert.DeserializeObject(jsonData);
foreach (dynamic rootObject in jsonValue)
{
theData.destLong.Value <-- use it anyway you want, store in a variable, etc.
// to get to each of the subSite in the rootObject
foreach (dynamic subSite in rootObject.subSites)
{
subSite.id.Value <-- returns an int based on your data
subSite.name.Value <-- returns a string based on your data
}
}
// where jsonData constains the json string you posted
The foreaeach is important because the data you posted will result into an array. You can also just do a jsonValue[0] but watch out for errors for null values, which you should be checking anyway starting with the returned json string.

write data from JSON in C#

I have JSON like this:
{
'surveys': [
{
'title': 'first',
'id': 100,
},
{
'title': 'second',
'id': 101,
},
{
'title': 'third',
'id': 102,
},
]
}
I want to have the output like this:
title: first
title: second
title: third
and my program in C# is like this:
WebClient client = new WebClient();
var json = client.DownloadString("http://www.test.com/api/surveys/?api_key=123");
Debug.WriteLine(json); //write all data from json
//add
var example = JsonConvert.DeserializeObject<Example>(json);
Debug.WriteLine(example.Data.Length);
class Example
{
public surveys[] Data { get; set; }
}
class surveys
{
public string title { get; set; }
public int id { get; set; }
}
I get this error:
Thrown: "Object reference not set to an instance of an object." (System.NullReferenceException) Exception Message = "Object reference not set to an instance of an object.", Exception Type = "System.NullReferenceException", Exception WinRT Data = ""
at this line: Debug.WriteLine(example.Data.Length);
where is the problem?
One problem I see is that your outer class has a property named Data, which is an array of 'surveys' objects, but your Json has a list of 'surverys' objects under the property 'surveys'. Hence the 'Data' property is never populated.
Consider the following C# class structure:
class Example
{
public survey[] surveys{ get; set; }//Data renames to surveys
}
class survey //Singular
{
public string title { get; set; }
public int id { get; set; }
}
Why can't you do so?:
JObject data = JObject.Parse(json);
foreach (var survey in data["surveys"].Children())
{
Debug.WriteLine("title: " + survey["title"]);
}
You need to use JSON.Net and use the class JsonConvert and the method DeserializeObject<T>.
If you run this:
JsonConvert.DeserializeObject<JObject>();
Then you will get back a list of de-serialized JObject objects.
Use, NuGet to download the package. I think it is called JSON.net.
Here is the weblink
WebClient client = new WebClient();
var json = client.DownloadString("http://www.test.com/api/surveys/?api_key=123");
Debug.WriteLine(json); //write all data from json
//add
var example = JsonConvert.DeserializeObject<Survey>(json);
Debug.WriteLine(example.length); // this could be count() instead.
class Survey
{
public string title { get; set; }
public int id { get; set; }
}
This should work!
Use json2csharp to generate c# classes from json.
You will also need to use Json.NET.
public class Survey
{
public string title { get; set; }
public int id { get; set; }
}
public class RootObject
{
public List<Survey> surveys { get; set; }
}
Then you can do:
var client = new WebClient();
string json = client.DownloadString(some_url);
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
foreach (Survey s in root.surveys)
{
// Do something with your survey
}
Don't forget to use Newtonsoft.Json namespace once you add a reference to it within your project.
using Newtonsoft.Json;
Edit: I have tested it using:
string json = "{'surveys': [{'title': 'first','id': 100,},{'title': 'second','id': 101,},{'title': 'third','id': 102,},]}";
instead of using the WebClient, and it works.

Categories