When I try to deserialize the following with the .NET JavaScriptDeserializer, I get the error message: Type 'People' is not supported for deserialization of an array
When I use JSON.NET like JsonConvert.DeserializeObject<List<People>>(args["xldata"]);, I get a more detailed error message:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'People' 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 '[0]', line 1, position 2.
I am using Linq-To-Entities, so I don't think I can add any attributes to it.
args["xldata"] is a Dictionary with "xldata" as the key and the JSON string below as the value.
[
[
{
"CarrierHeaderId": 17,
"DetailHeaderId": 54,
"tds_client": "0000000996",
"carr_no": "0000019",
"name": "John Doe ",
"entry_type": "F",
"carrier_type": "2",
"scac_code": "1A ",
"cert_no": "2d ",
"address": "123 orange boulevard ",
"city": "Orlando ",
"state": "St",
"zip": "33333 ",
"phone": "9993023938",
"epa_num": "123 ",
"fein": "AA ",
"host_carr_no": "BB ",
"host_route_cd": "1a3 ",
"country": "US",
"CarrierHeaderLastUpdate": "6/11/2013 11:07 AM",
"term_id": "TDSTES8",
"trailer_req": "0",
"truck_req": "0",
"access_from": "1159",
"access_to": "2359",
"access_days": "YNNYYYN",
"ins_exp_date": "12/20/13",
"locked": "",
"lockout_date": "",
"lockout_reason": "",
"st_license": "",
"st_permit": "",
"icc_permit": "",
"liab_amt": "",
"haz_mat_excl": "",
"veh_liab_exp": "",
"veh_liab_amt": "",
"excess_liab_exp": "",
"excess_liab_amt": "",
"work_comp_exp": "",
"work_comp_amt": "",
"host_locked": "",
"host_lockout_date": "",
"host_lockout_reason": "",
"po_relno_req": null,
"general_exp": "",
"general_amt": "",
"access_profile": "",
"max_load_amt": "",
"own_consumption": "",
"full_redirect": "",
"det_required": "",
"seal_processing": "",
"email_group": "",
"email_address": "",
"shipment_origin": "",
"auto_confirm": "",
"bulk_transaction_picklist": "",
"ExciseNo": "",
"ERP_Carrier": "",
"CarrierDetailLastUpdate": "6/11/2013 5:03 PM"
}
]
]
JsonConvert.DeserializeObject<List<List<People>>> should work.
Related
I am using Mapping object in asp.net core 6. Currently, I want to map two dictionaries in the asp .net core, one has value in key = null and one has value in key != null.
You can see my code below:
public async Task<IDictionary<string, object>> MappingDictionaries(IDictionary<string, object> sourceDict)
{
// Get dictionary from Repository, this dictionary has value in key = null;
var destinationDict = await _myRepository.GetMulti(x => x.ParentID == 0);
// sourceDict is passed by parameter variable and this dictionary has value != null;
}
How can I map properties and values from sourceDict to destinationDict? To check if the properties have been mapped, if yes return destinationDict, otherwise show a notification error.
My source dictionary:
"customerInfo": {
"CustomerName": "A",
"CustomerCode": "ABC",
"DateOfBirdth": "12/02/2020",
"Address": "D",
"PhoneNumber": "12345",
"Gender": "Nam",
"Email": "abc"
},
"provideTime": {
"Hour": "12:00",
"Day": "07",
"Month": "10",
"Year": "2022"
}
My destination dictionary:
"customerInfo": {
"CustomerName": "",
"CustomerCode": "",
"DateOfBirdth": "",
"Address": "",
"PhoneNumber": "",
"Gender": "",
"Email": ""
},
"provideTime": {
"Hour": "",
"Day": "",
"Month": "",
"Year": ""
}
Thanks for your support and sorry for my bad English!
I have the following error trying to deserialise a Json with Refit in a PCL :
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.List`1[UserItem]' 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 'user.id', line 1, position 42.
I think it comes from the Arrays returned for the interests ?
{
"error": {
"code": 0,
"msg": ""
},
"user": {
"id": "5",
"first_name": "test",
"last_name": "test",
"email": "a#gmail.com",
"auth_token": "****",
"date_of_birth": "0001-05-06 00:00:00",
"group_id": "1",
"group_name": null,
"postal_code": "56456",
"city": "Annecy",
"country": "France",
"facebook_id": null,
"facebook_img": null,
"status": null,
"is_activated": null,
"gcm_id": "GHJK",
"device_id": null,
"platform": "android",
"interest": ["1", "2"],
"profile_pic": "profile.jpg",
"cover_img": "cover.jpg",
"address": null,
"invoicing_address": "address",
"invoicing_city": "city",
"invoicing_country": "",
"invoicing_postal_code": "78654",
"gender": null,
"company_no": "1234",
"company_name": "",
"about_company": "",
"company_logo": "",
"company_legal_name": "lumao",
"company_contact_no": "",
"company_address": "",
"company_city": "",
"company_country": "",
"company_postal_code": "",
"vat_no": "",
"telephone": null,
"membership_status": null,
"contact_status": 2,
"company_interests": [],
"needs": ["not_implemented"]
}
}
EDIT :
Here is how I instantiate Refit :
Func<HttpMessageHandler, IFlairPlayApi> createClient = messageHandler =>
{
var client = new HttpClient(messageHandler)
{
BaseAddress = new Uri(ApiBaseAddress)
};
return RestService.For<IFlairPlayApi>(client);
};
NativeMessageHandler msgHandler = new NativeMessageHandler();
msgHandler.DisableCaching = true;
_speculative = new Lazy<IFlairPlayApi>(() => createClient(
new RateLimitedHttpMessageHandler(msgHandler, Priority.Speculative)
));
And how I call the service :
[Get("/getuser.json")]
Task<UserResponse> GetUser(int userid, int contact_id, string langval);
EDIT 2 :
I tried to change UserResponse to dynamic and then parse the dynamic object into a UserReponse, but it still strip the interests. And I would loose the benefit of using Refit :
[Get("/getuser.json")]
Task<dynamic> GetUser(int userid, int contact_id, string langval);
dynamic userObject = await FPApi.Speculative.GetUser(user.id, contact_id, FPEngine.Instance.Lang);
JObject jUser = userObject as JObject;
UserResponse response = jUser.ToObject<UserResponse>();
Am I doing it wrong ? isn't there a simple way to retrieve Arrays of strings ?
I had the same problem, I solved it as follows:
The service return, returns string, that is, the raw Json:
public interface IApiHgFinance
{
[Get("/taxes?key=minhachave")]
Task<string> GetTaxes();
}
And in the code where I call the service, I treat Json:
try
{
IApiHgFinance ApiHgFinance = Refit.RestService.For<IApiHgFinance>("https://api.hgbrasil.com/finance");
var result = await ApiHgFinance.GetTaxes();
var jo = Newtonsoft.Json.Linq.JObject.Parse(result);
var taxes = jo["results"].ToObject<itemTaxes[]>();
foreach (var item in taxes)
{
MessageBox.Show($"Taxa CDI : {item.Cdi} \nTaxa Selic : {item.Selic} \nData Atualização: {item.Date}",
"Atualização de informações", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show($"Erro: {ex.Message}", "Erro ao tentar recuperar as taxas do dia.", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
In this method, a JSON String will be returned from GetDataSetColumns() which called API from a Signage System(Xibo) to get dataset. And I want to parse it to JSON Object.
I googled it many times and found some people have same problem too. But it seems their solution are not working for me. Such as parsing to JArray or String.Trim()
public async Task<String> GetColumnIdByName(int dataSetId, String heading)
{
String columns = await GetDataSetColumns(dataSetId);
columns.Replace("[", "");
columns.Replace("]", "");
columns.TrimStart().TrimEnd();
**JObject json = JObject.Parse(columns);**
Debug.WriteLine(json);
foreach (KeyValuePair<string, JToken> pair in json)
{
if (pair.Key.ToString().Equals("dataSetColumnId"))
{
if(pair.Value.ToString().Equals(heading))
{
return pair.Value.ToString();
}
}
}
return null;
}
Here's the JSON returned from GETDataSetColumns method and shown in Debug.
And I cannot see there is any mistakes in this JSON String.
[
{
"dataSetColumnId": 8,
"dataSetId": 3,
"heading": "item_name",
"dataTypeId": 1,
"dataSetColumnTypeId": 1,
"listContent": null,
"columnOrder": "1",
"formula": null,
"dataType": "String",
"dataSetColumnType": "Value"
},
{
"dataSetColumnId": 9,
"dataSetId": 3,
"heading": "price",
"dataTypeId": 1,
"dataSetColumnTypeId": 1,
"listContent": null,
"columnOrder": "2",
"formula": null,
"dataType": "String",
"dataSetColumnType": "Value"
},
{
"dataSetColumnId": 12,
"dataSetId": 3,
"heading": "category",
"dataTypeId": 1,
"dataSetColumnTypeId": 1,
"listContent": null,
"columnOrder": "3",
"formula": null,
"dataType": "String",
"dataSetColumnType": "Value"
},
{
"dataSetColumnId": 15,
"dataSetId": 3,
"heading": "status",
"dataTypeId": 1,
"dataSetColumnTypeId": 1,
"listContent": null,
"columnOrder": "7",
"formula": null,
"dataType": "String",
"dataSetColumnType": "Value"
}
]
And I also inspected the value of variable by Debugging mode, is it normal to have '\n' and many blankspaces? Moreover, the String.Replace and String.TrimStart() aren't working.
Debugging Mode
The exception error happens after JObject.Parse.
Exception thrown: 'Newtonsoft.Json.JsonReaderException' in Newtonsoft.Json.dll
Exception thrown: 'Newtonsoft.Json.JsonReaderException' in mscorlib.dll
An exception of type 'Newtonsoft.Json.JsonReaderException' occurred in mscorlib.dll but was not handled in user code
Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
Is there any problem of my JSON string or the way of parsing?
Thanks for any help!
I found the answer from this post
I also found other answers online but all of them are not working.
Some of them proposed define a class and deserialize the object as that defined class. But I think it isn't the right way because the structure of JSON could be dynamic.
I transfer it to JArray and retrieve the objects from it as JObject.
And it works.
I saw these comments and I think the validity of JSON isn't the main point of my problem at all.
String columns = await GetDataSetColumns(dataSetId);
JArray jArr = (JArray)JsonConvert.DeserializeObject(columns);
foreach (JObject item in jArr)
{
if(heading.Equals(item["heading"].ToString()))
{
return item["dataSetId"].ToString();
}
}
Here's example of the JSON string and I get the value by key
{
"dataSetColumnId": 12,
"dataSetId": 3,
"heading": "category",
"dataTypeId": 1,
"dataSetColumnTypeId": 1,
"listContent": null,
"columnOrder": "3",
"formula": null,
"dataType": "String",
"dataSetColumnType": "Value"
}
i'm working for windows phone 8..
i need to retrieve the Json data from url and i need to display in an array..
my url have this jsondata like this..
{ id: 9
address: "abc"
city: " chennai"
contact1: ""
contact2: ""
country: " india"
description: ""
}
i would like to know how to retrieve this data and store it in an array?
here is the statements i used to retrieve the Json data.
private string REST_URL = "my url"; //i'm using my url here to extract the json data..
String servicePath = REST_URL + "/data/" + query;
Detail[] detail = JsonConvert.DeserializeObject<Detail[]>(servicePath);
return detail;
my complete Json data
[
{
"id": 01,
"address": "12asdf",
"city": " chennai",
"contact1": "",
"contact2": "",
"country": " india",
"description": "",
"name": " david",
"region": "",
"state": " 033",
"website": "",
"image": "",
"PrayerTime": {
"id": 01,
"PrayerTime1": "00:52",
"PrayerTime2": "21:04",
"PrayerTime3": "12:27",
"PrayerTime4": "05:35",
"PrayerTime5": "21:04",
"created_at": null,
"PrayerTime6": "04:01",
"updated_at": null,
"organization_id": 001
}
},.............
}
First ensure that your model is correct. As #Xyroid stated use json2csharp.com, which allows you to simply copy and paste your json and it will generate the corresponding c# code.
You can't give the URL to your parser, you will first have to download the JSON as string. To download the string simply use the HttpClient which you can even use in a PCL.
var httpClient = new System.Net.Http.HttpClient();
string jsonData = httpClient.GetStringAsync(url);
i have posted how to deserialize a json in c# but this is my question:
i got this json string :
data = #"[{""ShiftID"":""2"",""EmpName"":""dsdsfs""},{""ShiftID"":""4"",""EmpName"":""dsdsfd""}]";
and my code can deserialize it perfectly but well, if i receive this type :
data = #"[{
"Q6Option": null,
"Q5Comments": "",
"EndDate": "01/17/2012 12:57",
"Q4Comments": "",
"Active": 1,
"Q3Comments": "",
"Q8Option": null,
"Q2Comments": "",
"StartDate": "01/17/2012 12:57",
"Q3Option": null,
"Q5Option": null,
"Q1Comments": "",
"Q2Option": null,
"Station": "B1",
"Q7Option": null,
"SyncDate": null,
"ID": 1,
"Q8Comments": "",
"Q4Option": null,
"ShiftID": 1,
"EmpName": "CSM FName",
"Q1Option": null,
"Q7Comments": "",
"SyncStatus": 0,
"Q6Comments": "",
"EmpID": "111",
"createdAt": "2012-01-17T20:58:17.956Z",
"updatedAt": "2012-01-17T20:58:17.956Z",
"objectId": "XERFM5KrGv"
}]"
it doesnt work because of there is missing ""..
Well if you have an idea , thanks!
You can use the JavaScriptSerializer class that are supported from .NET framework 3.5
Reference link:
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
Sample link:
http://msdn.microsoft.com/en-us/library/bb412170.aspx
There are some sample json texts that are same as your issue:
{"__type":"Shape:#MyApp.Shapes","x":50,"y":70}