I have some json text which i would like to use to populate a gridview. I can get it working if i dont have the headers part of it in the json data but if i do i get an error. Can someone please help me, not sure where im going wrong
Error reading string. Unexpected token: StartObject. Path '[0].headers'
ASP.NET CODE
public class Emails
{
public string status { get; set; }
public string delivered_at { get; set; }
public string sender { get; set; }
public string email_ts { get; set; }
public string email_id { get; set; }
public string host { get; set; }
public string process_status { get; set; }
public string smtpcode { get; set; }
public string recipient { get; set; }
public string response { get; set; }
public string headers { get; set; }
}
List<Emails> myDeserializedObjList = (List<Emails>)Newtonsoft.Json.JsonConvert.DeserializeObject(strResult, typeof(List<Emails>));
gvRecords.DataSource = myDeserializedObjList;
gvRecords.DataBind();
JSON VALUE
[
{
"status": "ok",
"delivered_at": "2014-02-12T20:51:48.000059+00:00",
"sender": "abc#123.co.nz",
"headers": {
"subject": "Test No 1"
},
"email_ts": "2014-02-12T20:51:46.219800+00:00",
"email_id": "1WDgmY-4gfM00-Hj",
"host": "mx1.webhost.co.nz [119.47.119.2]",
"process_status": "completed",
"smtpcode": 250,
"recipient": "bob#123.co.nz",
"response": "250 2.0.0 Ok: queued as 8022160F4F"
},
{
"status": "hardbounce",
"delivered_at": "2014-02-12T20:55:32.000047+00:00",
"sender": "jim#123.co.nz",
"headers": {
"subject": "Test No 1"
},
"email_ts": "2014-02-12T20:55:30.028400+00:00",
"email_id": "1WDgqA-4gfLik-2I",
"host": "mx1.webhost.co.nz [119.47.119.2]",
"process_status": "completed",
"smtpcode": 550,
"recipient": "womble#123.co.nz",
"response": "550 5.1.1 <womble#123.co.nz>: Recipient address rejected: User unknown in virtual mailbox table"
}
]
There are some mistakes formatting your JSON data
First , You should use Angel Braces [ after the "header" property like that :
"headers":[ {
"subject": "Test No 1"
}],
Second : In your model class , you defined smtpcode as a string property while you passed it an int value inside your JSON data
"smtpcode": 250
It should be :
"smtpcode" : "250"
OR
public int smtpcode {get;set;} and keep it the same in JSON
Related
I have the following WebCleint to call a Restful web service inside my .net console application:-
try
{
using (WebClient wc = new WebClient())
{
wc.Encoding = Encoding.UTF8;
string url = "https://*****/paged?hapikey=*********&properties=website&properties=i_scan&limit=2";//web service url
string tempurl = url.Trim();
var json = wc.DownloadString(tempurl);//get the json
Marketing ipfd = JsonConvert.DeserializeObject<Marketing>(json);//deserialize
}
}
catch (Exception e)
{
//code goes here..
}
where i am using JSON.Net to Deserialize the json object, which will be as follow:-
{
"has-more": true,
"offset": 622438650,
"companies": [
{
"portalId": *******,
"companyId": *****,
"isDeleted": false,
"properties": {
"website": {
"value": "****.net",
"timestamp": 1520938239457,
"source": "CALCULATED",
"sourceId": null,
"versions": [
{
"name": "website",
"value": "*****.net",
"timestamp": 1520938239457,
"source": "CALCULATED",
"sourceVid": [
731938234
]
}
]
}
},
"additionalDomains": [],
"stateChanges": [],
"mergeAudits": []
},
{
"portalId": ******,
"companyId": ******,
"isDeleted": false,
"properties": {
"website": {
"value": "****.***.***",
"timestamp": 1512488590073,
"source": "CALCULATED",
"sourceId": null,
"versions": [
{
"name": "website",
"value": "****.***8.****",
"timestamp": 1512488590073,
"source": "CALCULATED",
"sourceVid": []
}
]
},
"i_scan": {
"value": "Yes",
"timestamp": 1543409493459,
"source": "******",
"sourceId": "**************",
"versions": [
{
"name": "i_scan",
"value": "Yes",
"timestamp": 1543409493459,
"sourceId": *****",
"source": "CRM_UI",
"sourceVid": [],
"requestId": "******"
}
]
}
},
"additionalDomains": [],
"stateChanges": [],
"mergeAudits": []
}
]
}
Here are my classes:-
public class Marketing
{
public Companies companies { get; set; }
}
public class Companies
{
public IList<string> companyId { get; set; }
public IList<Properties> properties { get; set; }
}
public class Properties
{
public IList<Website> website { get; set; }
public IList<I_Scan> i_scan { get; set; }
}
public class Website
{
public string value { get; set; }
}
public class i_Scan
{
public string value { get; set; }
}
but currently i am getting this exception, when i try to de-serialize the JSON object:-
Newtonsoft.Json.JsonSerializationException was caught
HResult=-2146233088
Message=Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MMarketing.Companies' 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 'companies', line 1, position 49.
Source=Newtonsoft.Json
StackTrace:
so i am not sure why JSON.NET is unable to do the Deserialize correctly, as in my case the classes are compatible with the returned json object??
At a first glance it looks like you switched two properties in Making them a List and vice versa.
public class Marketing
{
public List<Companies> companies { get; set; }
}
Is "companies": [ in the json, while "companyId": *****, is the id as a string, not array. Properties is not an array also, but the property versions of properties is.
public class Companies
{
public string companyId { get; set; }
public Properties properties { get; set; }
}
If I'm coming to json blind I like to use http://json2csharp.com/ to generate my class structure for me
public class Version
{
public string name { get; set; }
public string value { get; set; }
public object timestamp { get; set; }
public string source { get; set; }
public List<object> sourceVid { get; set; }
}
public class Website
{
public string value { get; set; }
public object timestamp { get; set; }
public string source { get; set; }
public object sourceId { get; set; }
public List<Version> versions { get; set; }
}
public class Version2
{
public string name { get; set; }
public string value { get; set; }
public long timestamp { get; set; }
public int sourceId { get; set; }
public string source { get; set; }
public List<object> sourceVid { get; set; }
public int requestId { get; set; }
}
public class IScan
{
public string value { get; set; }
public long timestamp { get; set; }
public int source { get; set; }
public int sourceId { get; set; }
public List<Version2> versions { get; set; }
}
public class Properties
{
public Website website { get; set; }
public IScan i_scan { get; set; }
}
public class Company
{
public int portalId { get; set; }
public int companyId { get; set; }
public bool isDeleted { get; set; }
public Properties properties { get; set; }
public List<object> additionalDomains { get; set; }
public List<object> stateChanges { get; set; }
public List<object> mergeAudits { get; set; }
}
public class Marketing
{
public bool has_more { get; set; }
public int offset { get; set; }
public List<Company> companies { get; set; }
}
var result = JsonConvert.DeserializeObject<Marketing>(json);
not really sure if I'm asking this in the correct manner. But I am doing a project for my university with CRM systems and API's.
Now I found Flurl to help me do my HTTP request. and it works great until I try and do a get all accounts to my free developer account to salesforce (i added some test accounts). The JSON I receive is this:
{
"objectDescribe": {
"activateable": false,
"createable": true,
"custom": false,
"customSetting": false,
"deletable": true,
"deprecatedAndHidden": false,
"feedEnabled": true,
"hasSubtypes": false,
"isSubtype": false,
"keyPrefix": "001",
"label": "Account",
"labelPlural": "Accounts",
"layoutable": true,
"mergeable": true,
"mruEnabled": true,
"name": "Account",
"queryable": true,
"replicateable": true,
"retrieveable": true,
"searchable": true,
"triggerable": true,
"undeletable": true,
"updateable": true,
"urls": {
"compactLayouts": "/services/data/v39.0/sobjects/Account/describe/compactLayouts",
"rowTemplate": "/services/data/v39.0/sobjects/Account/{ID}",
"approvalLayouts": "/services/data/v39.0/sobjects/Account/describe/approvalLayouts",
"defaultValues": "/services/data/v39.0/sobjects/Account/defaultValues?recordTypeId&fields",
"listviews": "/services/data/v39.0/sobjects/Account/listviews",
"describe": "/services/data/v39.0/sobjects/Account/describe",
"quickActions": "/services/data/v39.0/sobjects/Account/quickActions",
"layouts": "/services/data/v39.0/sobjects/Account/describe/layouts",
"sobject": "/services/data/v39.0/sobjects/Account"
}
},
"recentItems": [
{
"attributes": {
"type": "Account",
"url": "/services/data/v39.0/sobjects/Account/0015800000it9T3AAI"
},
"Id": "0015800000it9T3AAI",
"Name": "Test 5"
},
{
"attributes": {
"type": "Account",
"url": "/services/data/v39.0/sobjects/Account/0015800000it8eAAAQ"
},
"Id": "0015800000it8eAAAQ",
"Name": "Test 4"
},
{
"attributes": {
"type": "Account",
"url": "/services/data/v39.0/sobjects/Account/0015800000it8dbAAA"
},
"Id": "0015800000it8dbAAA",
"Name": "Test 3"
},
{
"attributes": {
"type": "Account",
"url": "/services/data/v39.0/sobjects/Account/0015800000it8dHAAQ"
},
"Id": "0015800000it8dHAAQ",
"Name": "Test 2"
},
{
"attributes": {
"type": "Account",
"url": "/services/data/v39.0/sobjects/Account/0015800000it8ciAAA"
},
"Id": "0015800000it8ciAAA",
"Name": "Test 1"
}
]
}
and the error I receive is the following:
Request to https://eu6.salesforce.com/services/data/v39.0/sobjects/Account/ failed.
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IEnumerable`1[InHollandCRMAPI.Models.AccountItem]'
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 'objectDescribe', line 1, position 18.
I also found this link on here:
Parsing from json to object using FLURL
but I can't seem to recreate this with my model:
public class AccountItem : ICRMItem
{
public Describe[] ObjectDescribe { get; set; }
public List<Recent> recentItems { get; set; }
public class Recent
{
public Attributes[] Attributes { get; set; }
public string Id { get; set; }
public string Name { get; set; }
}
public class Describe
{
public bool activateable { get; set; }
public bool createable { get; set; }
public bool custom { get; set; }
public bool customSetting { get; set; }
public bool deletable { get; set; }
public bool deprecatedAndHidden { get; set; }
public bool feedEnabled { get; set; }
public bool hasSubtypes { get; set; }
public bool isSubtype { get; set; }
public string keyPrefix { get; set; }
public string label { get; set; }
public string labelPlural { get; set; }
public bool layoutable { get; set; }
public bool mergeable { get; set; }
public bool mruEnabled { get; set; }
public string name { get; set; }
public bool queryable { get; set; }
public bool replicateable { get; set; }
public bool retrieveable { get; set; }
public bool searchable { get; set; }
public bool triggerable { get; set; }
public bool undeletable { get; set; }
public bool updateable { get; set; }
public Urls[] urls { get; set; }
}
}
and at last this is how de Deserialize is in my code
response = request.GetAsync();
responseData = await response.ReceiveJson<T>().ConfigureAwait(true);
Edit my controller class where the requests come in:
[HttpGet("{CRM}")]
public IEnumerable<ICRMItem> Get(string CRM)
{
if(CRM == "SalesForce")
{
ICRMService AccountGetAll = new AccountService();
var Account = AccountGetAll.With<AccountItem>().GetAll().ResponseData();
return Account;
}
}
After #Todd Menier his changes
as my response in Todd's message shamefully it didn't do the trick. and i still get this exception message.
Request to https://eu6.salesforce.com/services/data/v39.0/sobjects/Account/ ailed. Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type
'System.Collections.Generic.IEnumerable`1[InHollandCRMAPI.Models.AccountItem]' 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 'objectDescribe', line 1, position 18.
Edit
Todd Menier asked me for the path my code takes so here it is:
After I do my call it comes in my controller
ICRMService AccountGetAll = new AccountService();
var Account = AccountGetAll.With<AccountItem>().GetAll().ResponseData();
return Account;
Where after it goes into my service:
public ICRMServiceWithResource<T> With<T>(bool beta = false) where T : ICRMItem
{
var Uri = "https://eu6.salesforce.com/services/data/v39.0/";
return new SalesForceServiceWithResource<T>()
{
Resource = Resources.Resources.GetResource<T>(),
Uri = Uri
};
}
then it gets the Recources
public class Resources
{
public const string Accounts = "sobjects/Account/";
public static string GetResource<T>() where T : ICRMItem
{
var type = typeof(T);
if (type == typeof(AccountItem)) return Accounts;
and it gets into my GetAll function
public ICRMResponse<IEnumerable<T>> GetAll()
{
return Get<IEnumerable<T>>();
}
as you see it goes to a get function
private ICRMResponse<TOut> Get<TOut>(string id = "")
{
return DoRequest<TOut>(Resource + id, "GET", null).Result;
}
from where it goes into the DoRequest:
public async Task<ICRMResponse<T>> DoRequest<T>(string url, string method, object body)
{
ICRMResponse<T> result;
try
{
GetCRM(AppConfig.Key);
var request = Authorise(url);
Task<HttpResponseMessage> response;
T responseData;
switch (method.ToLower())
{
case "post":
if (body == null)
{
throw new ArgumentNullException("body");
}
response = request.PostJsonAsync(body);
responseData = await response.ReceiveJson<T>().ConfigureAwait(false);
break;
case "get":
response = request.GetAsync();
responseData = await response.ReceiveJson<T>().ConfigureAwait(true);
break;
from where it breaks and shows the message as state before
i'll check back around 16:00 GMT+1 or else Tuesday morning hope i gave you everything you needed
In your C# model, urls is an array, but it is not an array in the JSON representation; it is an object.
You didn't post the definition of your Urls class, but I'm going to guess it looks like this:
public class Urls
{
public string compactLayouts { get; set; }
public string rowTemplate { get; set; }
public string approvalLayouts { get; set; }
public string defaultValues { get; set; }
public string listviews { get; set; }
public string describe { get; set; }
public string quickActions { get; set; }
public string layouts { get; set; }
public string sobject { get; set; }
}
The JSON is returning a single object that looks like this, not a collection of them. So, in your Describe class, just drop the array and define it like this:
public Urls urls { get; set; }
UPDATE:
I didn't see this at first but there's a similar problem with objectDescribe and attributes. Those aren't arrays either, so don't define them that way in your C# model. Here's a summary of all changes:
public class AccountItem : ICRMItem
{
public Describe ObjectDescribe { get; set; }
...
public class Recent
{
public Attributes Attributes { get; set; }
...
}
public class Describe
{
...
public Urls urls { get; set; }
}
}
Soo, I just fixed the Error. Was trying to get a List of all Accounts. but salesforce already Lists (part) the Accounts for you.
The Issue was IEnumerable in the GetAll() function (wich works great for most CRM systems) but if you wanna get this done you'd need to change the IEnumerable<T> to just T and that would be the quick fix for SalesForce
The Next step for me is to generate a List of accounts with all account info (as most GetAll's work with CRM API's).
TL;DR
public ICRMResponse<IEnumerable<T>> GetAll()
{
return Get<IEnumerable<T>>();
}
should be
public ICRMResponse<T> GetAll() //Technicly isn't a GetAll But a Get
{
return DoRequest<T>(Resource, "GET", null).Result;
}
This is a Fix to this post not a fix to my eventual wish but I'll close this topic because else we will go off topic
I'm trying to send a List to my controller via Web API. I'm sending it as JSON via Postman. I'm 100% sure the JSON is correctly formatted. Still the usersList ends up null. I've tried without the [FromBody] attribute also.
The controller name is UserController, so the url is api/user/. Method used is Put.
public IHttpActionResult Put([FromBody]List<UserVm> usersList)
{
if (usersList.Count > 0)
{
_userService.UpdateUserRoles(usersList);
return Ok();
}
return BadRequest();
}
public class UserVm
{
public int Id { get; set; }
public string UserName { get; set; }
public string Name { get; set; }
public string Token { get; set; }
public string Icao { get; set; }
public string RefreshToken { get; set; }
public int ExpiresIn { get; set; }
public List<Role> Roles { get; set; }
}
[
{
"id": 0,
"username": "banji",
"name": "baji",
"token": "bajz",
"icao": "poffe",
"refreshtoken": "konna",
"expiresin": 0,
"roles": [{
"id": 0,
"department": "asd",
"isadmin": false
}]
},
{
"id": 0,
"username": "banji",
"name": "baji",
"token": "bajz",
"icao": "poffe",
"refreshtoken": "konna",
"expiresin": 0,
"roles": [{
"id": 0,
"department": "asd",
"isadmin": false
}]
}
]
Suggestions on what I'm doing wrong are much appreciated.
I just copied what you posted and tried here. It works fine.
And the code:
public class UserVm
{
public int Id { get; set; }
public string UserName { get; set; }
public string Name { get; set; }
public string Token { get; set; }
public string Icao { get; set; }
public string RefreshToken { get; set; }
public int ExpiresIn { get; set; }
public List<Role> Roles { get; set; }
}
public class Role
{
public int Id { get; set; }
public string Department { get; set; }
public bool IsAdmin { get; set; }
}
public class UserController : ApiController
{
public IHttpActionResult Put([FromBody]List<UserVm> usersList)
{
if (usersList.Count > 0)
{
//_userService.UpdateUserRoles(usersList);
return Ok();
}
return BadRequest();
}
}
The postman data looks the same you posted too:
Do you have a default api route? Like:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
PS: It's a nice practice to use /resource/id when you use put. You are saying that you are going to change the resource with the given id, or you are going to create a resource with that id. The verb PUT is idempotent, so it should have always the exact same return. Thats why it's used more offen to do updates intead of creating resources.
I found the solution to my problem. I had forgotten to have an parameterless constructor..
I am using JSON.NET (Newtonsoft.Json) to deserialize my JSON into a .NET object - here's my JSON string:
{
"SafetyReport": {
"SafetyData": [{
"Unsafe": "YES",
"CategoryName": "Body Mechanics",
"CategoryData": "Grip / Force",
"Safe": "NO"
}, {
"Unsafe": "YES",
"CategoryName": "Position of People",
"CategoryData": "Falling",
"Safe": "NO"
}, {
"Unsafe": "YES",
"CategoryName": "Position of People",
"CategoryData": "Other",
"Safe": "YES"
}],
"SafeActsObserved": "APPLE",
"UnsafeActsObserved": "OK",
"Date": "11 / 11 / 1988",
"ObserverName": "Bob",
"ObserverGroup": "TEST",
"LocationAreaRegion": "Nowhere",
"Email": "abc#abc.com"
}
}
Here's my C# code - please note that the jsonData string contains exactly the JSON above, just in a single line. I've already verified this:
Once I step past the deserialization, here's what's in my SafetyReport object:
Finally, here are my class definitions for SafetyReport and SafetyData:
public class SafetyReport
{
IList<SafetyData> SafetyData { get; set; }
string SafeActsObserved { get; set; }
string UnsafeActsObserved { get; set; }
string Date { get; set; }
string ObserverName { get; set; }
string ObserverGroup { get; set; }
string LocationAreaRegion { get; set; }
string Email { get; set; }
}
public class SafetyData
{
string Unsafe { get; set; }
string Safe { get; set; }
string CategoryName { get; set; }
string CategoryData { get; set; }
}
QUESTION: What am I doing wrong?
Ok I got it working, multiple things might have been wrong, here's what I did:
Added public modifier to every field.
Removed Safetyreport from JSON
Changed all doublequotes(") to quotes (')
Try this:
class Program
{
static void Main(string[] args)
{
string json = #"{
'SafetyData': [{
'Unsafe': 'YES',
'CategoryName': 'Body Mechanics',
'CategoryData': 'Grip / Force',
'Safe': 'NO'
}, {
'Unsafe': 'YES',
'CategoryName': 'Position of People',
'CategoryData': 'Falling',
'Safe': 'NO'
}, {
'Unsafe': 'YES',
'CategoryName': 'Position of People',
'CategoryData': 'Other',
'Safe': 'YES'
}],
'SafeActsObserved': 'APPLE',
'UnsafeActsObserved': 'OK',
'Date': '11 / 11 / 1988',
'ObserverName': 'Bob',
'ObserverGroup': 'TEST',
'LocationAreaRegion': 'Nowhere',
'Email': 'abc#abc.com'
}
";
SafetyReport sr = JsonConvert.DeserializeObject<SafetyReport>(json);
Console.ReadLine();
}
}
public class SafetyReport
{
public IList<SafetyData> SafetyData { get; set; }
public string SafeActsObserved { get; set; }
public string UnsafeActsObserved { get; set; }
public string Date { get; set; }
public string ObserverName { get; set; }
public string ObserverGroup { get; set; }
public string LocationAreaRegion { get; set; }
public string Email { get; set; }
}
public class SafetyData
{
public string Unsafe { get; set; }
public string Safe { get; set; }
public string CategoryName { get; set; }
public string CategoryData { get; set; }
}
Maybe the problem is the first field of the JSON, you haven't to set witch class you will deserialize, you have to set the attribute names to identify them. Try with this json.
{
"SafetyData": [{
"Unsafe": "YES",
"CategoryName": "Body Mechanics",
"CategoryData": "Grip / Force",
"Safe": "NO"
}, {
"Unsafe": "YES",
"CategoryName": "Position of People",
"CategoryData": "Falling",
"Safe": "NO"
}, {
"Unsafe": "YES",
"CategoryName": "Position of People",
"CategoryData": "Other",
"Safe": "YES"
}],
"SafeActsObserved": "APPLE",
"UnsafeActsObserved": "OK",
"Date": "11 / 11 / 1988",
"ObserverName": "Bob",
"ObserverGroup": "TEST",
"LocationAreaRegion": "Nowhere",
"Email": "abc#abc.com"
}
Hope it helps.
I'm trying to parse a nested JSON string returned from the GCM (Google Could Messaging) server using VB.NET. The JSON string looks like this:
{ "multicast_id": 216,
"success": 3,
"failure": 3,
"canonical_ids": 1,
"results": [
{ "message_id": "1:0408" },
{ "error": "Unavailable" },
{ "error": "InvalidRegistration" },
{ "message_id": "1:1516" },
{ "message_id": "1:2342", "registration_id": "32" },
{ "error": "NotRegistered"}
]
}
I would like to get the results array in the above string.
I found the following example helpful, example but it does not show how to get to the nested parts, specifically message_id, error and registration_id inside the results array.
Thanks
I'll give an answer using c# and Json.net
var jobj = JsonConvert.DeserializeObject<Response>(json);
You can also use JavaScriptSerializer
var jobj2 = new JavaScriptSerializer().Deserialize<Response>(json);
public class Result
{
public string message_id { get; set; }
public string error { get; set; }
public string registration_id { get; set; }
}
public class Response
{
public int multicast_id { get; set; }
public int success { get; set; }
public int failure { get; set; }
public int canonical_ids { get; set; }
public List<Result> results { get; set; }
}