NewtonSoft JSON does not parse referenced items in an array - json

I writing an web API which excepts JSON with references, I am using JsonPropertyAttribute and JsonObjectAttribute to mark properties/classes which can be refereed by some other property.
when i am receiving data from API it is working as expected, having corresponding $id and $ref property set in JSON. But when I post same JSON date to API it is not parsing all data back. Bellow is data I am receiving from API and same I am posting back.
{
"GeneralDetails": {
"Description": "23",
"ScheduleInfo": {
"ScheduleFrequency": 701,
"ScheduledDay": null,
"ScheduledMonth": null,
"ScheduledTime": "2018-04-10T21:30:01"
},
"ImagePath": "",
"BrandId": 23,
"Name": "23",
"Id": 29
},
"TargetDetails": {
"Period": 0,
"Type": 2701,
"Targets": [
{
"TierId": 34,
"Value": 29
}
]
},
"PointsDetails": [
{
"BooleanExperession": {
"$id": "1",
"$type": "Payback.TradeTool.Entities.Model.Offer.OfferRuleBooleanExpression, Payback.TradeTool.Entities",
"Variable1": {
"$id": "2",
"$type": "Payback.TradeTool.Entities.Model.Offer.OfferRulePreDefinedVariable, Payback.TradeTool.Entities",
"GroupId": 2,
"Type": 12,
"AvailableOperant": 289,
"Description": "Product SKU",
"Name": "Product SKU",
"Id": 67
},
"Variable2": {
"$id": "3",
"$type": "Payback.TradeTool.Entities.Model.Offer.OfferRuleConstant`1[[System.String, mscorlib]], Payback.TradeTool.Entities",
"Value": "23",
"Type": 9,
"AvailableOperant": 289,
"Description": "2323",
"Name": "2323",
"Id": 132
},
"Operation": 1,
"Type": 130,
"AvailableOperant": 0,
"Description": "23",
"Name": "23",
"Id": 133
},
"Value": 23,
"Id": 16,
"Type": 0,
"ValueX": null
}
],
"Constants": [
{
"$id": "4",
"Value": "rty",
"Type": 9,
"AvailableOperant": 289,
"Description": "rty",
"Name": "yurt",
"Id": 130
},
{
"$id": "5",
"Value": 23,
"Type": 17,
"AvailableOperant": 231,
"Description": "23",
"Name": "ewe",
"Id": 131
},
{
"$ref": "3"
}
],
"BooleanExpressions": [
{
"$ref": "1"
}
],
}
when i am posting back Constants with $id 4 and 5 are not in parsed data. However if I refer them in some other property, then they are also parsing.
EDIT:
below is my class structure
public class OfferDetails
{
public OfferDetails()
{
GeneralDetails = new OfferGeneralDetails();
TargetDetails = new OfferTargetDetails();
PointsDetails = new List<OfferPointsDetails>();
Constants = new List<OfferRuleConstant>();
BooleanExpressions = new List<OfferRuleBooleanExpression>();
Variables = new Dictionary<string, List<OfferRulePreDefinedVariable>>();
}
public OfferGeneralDetails GeneralDetails { get; set; }
public OfferTargetDetails TargetDetails { get; set; }
[JsonProperty(ItemTypeNameHandling = TypeNameHandling.All)]
public List<OfferPointsDetails> PointsDetails { get; set; }
[JsonProperty(IsReference = false, ItemTypeNameHandling = TypeNameHandling.All)]
public List<OfferRuleConstant> Constants { get; set; }
[JsonProperty(ItemTypeNameHandling = TypeNameHandling.All,IsReference = false)]
public List<OfferRuleBooleanExpression> BooleanExpressions { get; set; }
public Dictionary<string, List<OfferRulePreDefinedVariable>> Variables { get; set; }
}
[JsonObject(ItemTypeNameHandling = TypeNameHandling.All, IsReference = true)]
public class OfferRuleConstant<T> : OfferRuleConstant
{
public OfferRuleConstant()
{
Type = RuleVariableType.Constant;
}
public T Value { get => (T)_value; set=> _value = value;}
public override string ToString()
{
return Value.ToString();
}
}
public abstract class OfferRuleConstant : OfferRuleVariable, ISeprateStringReprsentation
{
protected object _value;
public string StringReprsentation { get ; set ; }
}
[JsonObject(IsReference = true, ItemTypeNameHandling = TypeNameHandling.All)]
public class OfferRuleVariable : NamedEntity<long>
{
public OfferRuleVariable()
{
Type = RuleVariableType.Variable;
}
public RuleVariableType Type { get; set; }
public RuleOperantEnum AvailableOperant { get; set; }
public string Description { get; set; }
// public int GroupId { get; set; }
}
[JsonObject(IsReference = true, ItemTypeNameHandling = TypeNameHandling.All)]
public class OfferRulePreDefinedVariable : OfferRuleVariable
{
public int GroupId { get; set; }
}
public interface ISeprateStringReprsentation
{
string StringReprsentation { get; set; }
}
It is possible that I have made certain changes in model (Added a new Property, in a few class and also have changed some attribute while trying to fix above issue).
so, this is updated JSON I am trying to parse:
{
"$id":0,
"GeneralDetails":{
"$id":1,
"ScheduleInfo":{
"$id":2,
"ScheduleFrequency":701,
"ScheduledDay":null,
"ScheduledMonth":null,
"ScheduledTime":null,
"ScheduledTimeS":null
},
"Name":"tuy",
"Description":"ty"
},
"BooleanExpressions":[
{
"$id":3,
"$type":"Payback.TradeTool.Entities.Model.Offer.OfferRuleBooleanExpression, Payback.TradeTool.Entities",
"Type":130,
"Variable1":{
"$id":4,
"Id":46,
"Name":"Transaction DateTime",
"Type":100,
"AvailableOperant":55,
"Description":"Transaction DateTime"
},
"Variable2":{
"$id":5,
"$type":"Payback.TradeTool.Entities.Model.Offer.OfferRuleConstant`1[[System.DateTime, mscorlib]], Payback.TradeTool.Entities",
"Type":97,
"Value":"2018-04-19T10:36:02.000Z",
"Name":"6",
"AvailableOperant":7,
"Description":"6",
"StringReprsentation":"4/19/2018, 4:06:02 PM"
},
"Operation":1,
"AvailableOperant":224,
"Name":"tuy",
"Description":"uy",
"StringReprsentation":"(Transaction DateTime EqualTo 4/19/2018, 4:06:02 PM)"
},
{
"$id":6,
"$type":"Payback.TradeTool.Entities.Model.Offer.OfferRuleBooleanExpression, Payback.TradeTool.Entities",
"Type":130,
"Variable1":{
"$id":7,
"Id":48,
"Name":"Transaction Month",
"Type":4100,
"AvailableOperant":57,
"Description":"Transaction Month"
},
"Variable2":{
"$id":8,
"$type":"Payback.TradeTool.Entities.Model.Offer.OfferRuleListConstant`1[[System.Int32, mscorlib]], Payback.TradeTool.Entities",
"Type":5649,
"Value":[
2,
4,
3
],
"Name":"13",
"AvailableOperant":40,
"Description":"33",
"StringReprsentation":"February,April,March"
},
"Operation":8,
"AvailableOperant":224,
"Name":"tyu",
"Description":"yu",
"StringReprsentation":"(Transaction Month In February,April,March)"
}
],
"TargetDetails":{
"$id":9,
"Period":701,
"Type":2701,
"Targets":[
{
"$id":10,
"TierId":34,
"Value":1
},
{
"$id":11,
"TierId":86,
"Value":2
},
{
"$id":12,
"TierId":87,
"Value":3
},
{
"$id":13,
"TierId":88,
"Value":4
}
]
},
"PointsDetails":[
{
"$id":14,
"BooleanExperession":{
"$ref":"3"
},
"Type":1,
"Value":45,
"ValueX":4
}
],
"Constants":[
{
"$id":15,
"$type":"Payback.TradeTool.Entities.Model.Offer.OfferRuleConstant`1[[System.Int32, mscorlib]], Payback.TradeTool.Entities",
"Type":17,
"Value":"8",
"Name":"8",
"AvailableOperant":231,
"Description":"8",
"StringReprsentation":"8"
},
{
"$id":16,
"$type":"Payback.TradeTool.Entities.Model.Offer.OfferRuleListConstant`1[[System.Int32, mscorlib]], Payback.TradeTool.Entities",
"Type":263697,
"Name":"2",
"AvailableOperant":40,
"Value":[
1201,
1202
],
"Description":"2",
"StringReprsentation":"Male,Female"
},
{
"$id":17,
"Type":1049617,
"Value":1501,
"StringReprsentation":"Dealer",
"$type":"Payback.TradeTool.Entities.Model.Offer.OfferRuleConstant`1[[System.Int32, mscorlib]], Payback.TradeTool.Entities",
"Description":"2",
"Name":"1"
},
{
"$ref":"8"
},
{
"$id":18,
"$type":"Payback.TradeTool.Entities.Model.Offer.OfferRuleRangeConstant`1[[System.Int32, mscorlib]], Payback.TradeTool.Entities",
"Type":5393,
"Value":{
"$id":19,
"From":1,
"To":6
},
"Name":"12",
"AvailableOperant":16,
"Description":"12",
"StringReprsentation":"January AND June"
},
{
"$id":20,
"$type":"Payback.TradeTool.Entities.Model.Offer.OfferRuleConstant`1[[System.Int32, mscorlib]], Payback.TradeTool.Entities",
"Type":5137,
"Value":2,
"Name":"11",
"AvailableOperant":33,
"Description":"11",
"StringReprsentation":"February"
},
{
"$id":21,
"$type":"Payback.TradeTool.Entities.Model.Offer.OfferRuleListConstant`1[[System.Int32, mscorlib]], Payback.TradeTool.Entities",
"Type":3601,
"Value":[
1,
2,
3,
0
],
"Name":"10",
"AvailableOperant":40,
"Description":"33",
"StringReprsentation":"Tuesday,Wednesday,Thursday,Monday"
},
{
"$id":22,
"$type":"Payback.TradeTool.Entities.Model.Offer.OfferRuleRangeConstant`1[[System.Int32, mscorlib]], Payback.TradeTool.Entities",
"Type":3345,
"Value":{
"$id":23,
"From":0,
"To":4
},
"Name":"9",
"AvailableOperant":231,
"Description":"9",
"StringReprsentation":"Monday AND Friday"
},
{
"$id":24,
"$type":"Payback.TradeTool.Entities.Model.Offer.OfferRuleConstant`1[[System.Int32, mscorlib]], Payback.TradeTool.Entities",
"Type":3089,
"Value":0,
"Name":"7",
"AvailableOperant":225,
"Description":"7",
"StringReprsentation":"Monday"
},
{
"$ref":"5"
},
{
"$id":25,
"$type":"Payback.TradeTool.Entities.Model.Offer.OfferRuleConstant`1[[System.DateTime, mscorlib]], Payback.TradeTool.Entities",
"Type":33,
"Value":"2018-04-04T10:36:02.000Z",
"Name":"5",
"AvailableOperant":7,
"Description":"5",
"StringReprsentation":"4/4/2018"
},
{
"$id":26,
"$type":"Payback.TradeTool.Entities.Model.Offer.OfferRuleConstant`1[[System.Int32, mscorlib]], Payback.TradeTool.Entities",
"Type":17,
"Value":"4",
"Name":"4",
"AvailableOperant":231,
"Description":"4",
"StringReprsentation":"4"
},
{
"$id":27,
"$type":"Payback.TradeTool.Entities.Model.Offer.OfferRuleConstant`1[[System.String, mscorlib]], Payback.TradeTool.Entities",
"Type":9,
"Name":"3",
"AvailableOperant":289,
"Value":"3",
"Description":"3",
"StringReprsentation":"3"
}
],
"Variables":{
"$id":28
}
}
most of the Constants are parsing, but corresponding to "$id":17 is not in list.

after a few tries, i was able to find my mistake, It was "$id" property in json. which is number but in original JSON generated from API, it was string.
so, i changed my javaScript code generating JSON and it worked.
However I was unable to understand why it failed. when i posted with same data as generated form API initially, may be i just got confused.

Related

Cannot deserialize the current JSON object .Net Core 5

I have a .Net Core 5 solution that is largely he same as another previous, working solution. In both the controllers are .Net Core 5. In the previous, working one, the services, models and view models are in a 4.7 project. Most of the new solution is working, except for one controller that takes a nested (master/detail) JSON sent in the body of the request. The service is set up to deserialize the JSON into a dataset. The JSON shows as valid in the jsonlint.com validator.
However, I keep getting this error in Postman:
"Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IList`1[Sage100_API.ViewModels.APInvoiceReq]' 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 'APInvoiceRequest', line 2, position 21."
[JsonObjectAttribute] is already in place in the viewmodels involved.
The error occurs when stepping off the final curly bracket in this code in the controller:
public APInvoiceResponseController(IAPInvoiceService apInvoiceService, IOptions<AppSettingsModel> app)
{
APInvoiceService = apInvoiceService;
AppSettings = app;
}
What is different between core 5 and 4.7 in deserializing in NewtonSoft JSON?
edit: adding JSON and code
JSON:
{
"APInvoices": {
"APInvoice": [
{
"APDivisionNo": "00",
"APVendorNo": "0000006",
"PayeeTermsCd": "00",
"HoldPayment": "N",
"SeparateCheck": "N",
"InvoiceNo": "12345",
"InvoiceDate": "2022-04-06",
"BatchNmbr": "490",
"TotalAmount": 150,
"APInvoiceDetails": {
"APInvoiceDetail": [
{
"InvoiceNo": "12345",
"Line": "1",
"Amount": "25.7500",
"GLAcctID": "5000-00-10",
"Comment": "line 1 comment",
"BatchNmbr": "490"
},
{
"InvoiceNo": "12345",
"Line": "2",
"Amount": "75.2500",
"GLAcctID": "5000-00-10",
"Comment": "line 2 comment",
"BatchNmbr": "490"
},
{
"InvoiceNo": "12345",
"Line": "3",
"Amount": "49.00",
"GLAcctID": "5000-00-10",
"Comment": "line 3 comment",
"BatchNmbr": "490"
}
]
},
{
"APDivisionNo": "00",
"APVendorNo": "0000006",
"PayeeTermsCd": "00",
"HoldPayment": "N",
"SeparateCheck": "N",
"InvoiceNo": "12346",
"InvoiceDate": "2022-04-06",
"BatchNmbr": "490",
"TotalAmount": 150,
"APInvoiceDetails": {
"APInvoiceDetail": [
{
"InvoiceNo": "12345",
"Line": "1",
"Amount": "25.7500",
"GLAcctID": "5000-00-10",
"Comment": "line 1 comment",
"BatchNmbr": "490"
},
{
"InvoiceNo": "12345",
"Line": "2",
"Amount": "75.2500",
"GLAcctID": "5000-00-10",
"Comment": "line 2 comment",
"BatchNmbr": "490"
},
{
"InvoiceNo": "12345",
"Line": "3",
"Amount": "49.00",
"GLAcctID": "5000-00-10",
"Comment": "line 3 comment",
"BatchNmbr": "490"
}
]
}
}
]
}
}
Controller:
{
[ApiController]
public class APInvoiceResponseController : ControllerBase
{
//private readonly S100Entities Context;
private readonly IAPInvoiceService APInvoiceService;
private readonly IOptions<AppSettingsModel> AppSettings;
public APInvoiceResponseController(IAPInvoiceService apInvoiceService, IOptions<AppSettingsModel> app)
{
APInvoiceService = apInvoiceService;
AppSettings = app;
}
[HttpPost]
[Route("apinvoice")]
public async Task<IActionResult> Basic([FromBody] IList<APInvoiceReq> apInvoice)
{
try
{
var APInvoices = await APInvoiceService.PostAPInvoices(apInvoice);
try
{
if (apInvoice == null)
{
return BadRequest("Missing transaction data.");
}
if (APInvoices == null)
{
return NotFound();
}
return Ok(APInvoices);
}
catch (System.Exception e)
{
Serilog.Log.Error("Error in APInvoices", e);
APInvoices.SuccessErrorWarningResult.AddError(666, e.ToString());
return Ok(APInvoices);
}
}
catch (System.Exception e)
{
Serilog.Log.Error("Error in APInvoices", e);
return BadRequest();
}
}
}
}
APInvoiceReq class:
{
[JsonObjectAttribute]
[JsonArray]
[Serializable]
public class APInvoiceReq : S100Object<APInvoiceReq>
{
public string APDivisionNo { get; set; }
public string APVendorNo { get; set; }
public string PayeeTermsCd { get; set; }
public string HoldPayment { get; set; }
public string SeparateCheck { get; set; }
public string InvoiceNo { get; set; }
public DateTime InvoiceDate { get; set; }
public string InvoiceComment { get; set; }
public int BatchNmbr { get; set; } //UDF_BATCH_NO
public decimal TotalAmount { get; set; }
public IEnumerable<APInvoiceDetail> APInvoiceDetails { get; set; }
}
}

Having issues creating proper class for JSON.Net Deserialization of complex object. Receiving {"Cannot deserialize the current JSON array

This is a VB.Net project. Cannot seem to get the class library correct for deserializing the response string to the classes.
Error we receive when we try to deserialize is:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'blahblah_Framework_Root.blahblah+Tokenscopelist'
because the type requires a JSON object (e.g. {""name"":""value""}) to deserialize correctly.
Sample response trying to deserialize:
{
"data": {
"expiresAt": "2021-11-27T01:12:05.000Z",
"createdAt": "2021-11-13T01:12:05.000Z",
"identityId": 2347335,
"identity": {
"id": 2347335,
"namespace": {
"id": 7760,
"nickname": "org:random-parking"
}
},
"tokenScopeList": [
{
"org": {
"id": 5995,
"name": "RANDOM Parking",
"opal": "opal:prod:helium:alpha:5995:org:5995",
"parentOrg": null,
"packagePlans": [
{
"id": 50,
"package": {
"id": 14,
"name": "Additional Users Over 500",
"packageFeatures": [
{
"config": null,
"id": 147,
"feature": {
"id": 1,
"name": "Users Included",
"code": "users"
}
}
]
},
"isSelected": true
},
{
"id": 54,
"package": {
"id": 15,
"name": "Elevator I/O Boards",
"packageFeatures": [
{
"config": null,
"id": 175,
"feature": {
"id": 21,
"name": "Elevator I/O Boards",
"code": "elevatorIoBoards"
}
}
]
},
"isSelected": true
},
{
"id": 38,
"package": {
"id": 11,
"name": "Premium",
"packageFeatures": [
{
"config": {
"count": 500
},
"id": 91,
"feature": {
"id": 1,
"name": "Users Included",
"code": "users"
}
},
{
"config": {
"count": 1000000
},
"id": 92,
"feature": {
"id": 2,
"name": "Administrators",
"code": "administrators"
}
}
]
},
"isSelected": true
}
]
},
"user": {
"id": 2502299,
"opal": "opal:prod:helium:alpha:5995:user:2502299"
},
"scope": [
"o5995-admin:r",
"o5995-admin:w",
"o5995-configurations:r",
"o5995-configurations:w",
"o5995-dash:r",
"o5995-dash:w",
"o5995-videoProviderPlayback:w"
]
},
{
"org": {
"id": null,
"name": null
},
"user": {
"id": null,
"opal": null
},
"scope": [
"i2347335:r",
"i2347335:w"
]
}
],
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZGVw"
},
"meta": {
"accessToken": null
}
}
Using this class definition
Public Class RootobjectLogin
Public Property data As DataumLogin
Public Property meta As Meta
End Class
Public Class DataumLogin
Public Property expiresAt As Date
Public Property createdAt As Date
Public Property identityId As Integer
Public Property identity As Identity
Public Property tokenScopeList() As Tokenscopelist
Public Property token As String
End Class
Public Class Tokenscopelist
Public Property org As Org
Public Property user As User
Public Property scope() As String
End Class
Public Class Packageplan
Public Property id As Integer
Public Property package As Package
Public Property isSelected As Boolean
End Class
Public Class Package
Public Property id As Integer
Public Property name As String
Public Property packageFeatures() As New List(Of Packagefeature)
End Class
Public Class Packagefeature
Public Property config As Config
Public Property id As Integer
Public Property feature As Feature
End Class
Public Class Config
Public Property count As Integer
End Class
Public Class Feature
Public Property id As Integer
Public Property name As String
Public Property code As String
End Class
Public Class User
Public Property id As Integer
Public Property opal As String
End Class
Public Class Org
Public Property id As Integer
Public Property name As String
Public Property opal As String
Public Property parentOrg As Object
Public Property packagePlans() As New List(Of Packageplan)
End Class
Public Class Meta
Public Property accessToken As Accesstoken
End Class
Ideas?

HubSpot API POST contacts in batches

I am using the API to communicate batches of contacts using the endpoint /contacts/v1/contact/batch/
I get an error message response which reads#
{"status":"error", "message":"Invalid input JSON on line 1, column 1: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token","correlationId":"3c1488a8-24f5-4e1c-b506-18edcd870065","requestId":"a85c3ea88b60a7d0e3cfe5736c819b11"}
The JSON i am sending is valid. I've checked and double checked.
Please help :(
My output is below
[
{
"email": "twst#email.com",
"properties": [
{
"property": "company",
"value": "Test"
},
{
"property": "website",
"value": "www.test.com"
},
{
"property": "firstname",
"value": "Carl"
},
{
"property": "lastname",
"value": "Swann"
},
{
"property": "jobtitle",
"value": "Dr"
},
{
"property": "phone",
"value": "0789654321"
},
{
"property": "product",
"value": "Khaos Control Hybrid"
},
{
"property": "eventList_2019",
"value": "Spring Fair"
}
]
},
{
"email": "email#yes .com",
"properties": [
{
"property": "company",
"value": "Another one"
},
{
"property": "website",
"value": "www.a.ither.com"
},
{
"property": "firstname",
"value": "Anither"
},
{
"property": "lastname",
"value": "One"
},
{
"property": "jobtitle",
"value": "Com"
},
{
"property": "phone",
"value": "0789675341"
},
{
"property": "product",
"value": "Khaos Control Hybrid"
},
{
"property": "eventList_2019",
"value": "Spring Fair"
}
]
},
{
"email": "keeley#sophieallport.com",
"properties": [
{
"property": "company",
"value": "Sophie Allport"
},
{
"property": "website",
"value": "www.sophieallport.com"
},
{
"property": "firstname",
"value": "Keeley"
},
{
"property": "lastname",
"value": "Walters"
},
{
"property": "jobtitle",
"value": "Accounts "
},
{
"property": "phone",
"value": "01778235648"
},
{
"property": "product",
"value": "Khaos Control Hybrid"
},
{
"property": "eventList_2019",
"value": "Spring Fair"
}
]
}
]
I found the source code I used and will try my best to explain my implementation of it for you.
The application I created was a mobile app that is used by companies to capture information about new prospects and send that information into their HubSpot account.
The main application contains a class of Prospect which defines the information we want to obtain about a prospect
public class Prospect
{
public string CompanyName { get; set; }
public string Website { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string JobTitle { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Products { get; set; }
public string Notes { get; set; }
public string ContactOwner { get; set; }
public string ShowName { get; set; }
}
The component of the application which is relevant to the question you asked contains 2 classes:
public class HubSpotProspect
{
public string email { get; set; }
public List<Property> properties { get; set; }
}
public class Property
{
public string property { get; set; }
public string value { get; set; }
}
The following code gets a list of all the prospects then iterates through them to assign the correct attribute values and translates then into a new list of HubSpotProspect. We then serialise this list into json and pass it to the function that communicates with HubSpot API.
List<Prospect> _pList = _prospectList.GetProspectList(ShowName);
List _hsProspectList = new List();
foreach (Prospect p in _pList)
{
HubSpotProspect _hsp = new HubSpotProspect();
_hsp.email = p.Email;
_hsp.properties = new List<Property>();
_hsp.properties.Add(new Property { property = "company", value = p.CompanyName });
_hsp.properties.Add(new Property { property = "website", value = p.Website });
_hsp.properties.Add(new Property { property = "firstname", value = p.FirstName });
_hsp.properties.Add(new Property { property = "lastname", value = p.LastName });
_hsp.properties.Add(new Property { property = "jobtitle", value = p.JobTitle });
_hsp.properties.Add(new Property { property = "phone", value = p.Phone });
_hsp.properties.Add(new Property { property = "product", value = p.Products });
_hsp.properties.Add(new Property { property = "event_list_2019", value = p.ShowName });
_hsp.properties.Add(new Property { property = "hubspot_owner_id", value = _userProfile.GetContactOwner() });
_hsProspectList.Add(_hsp);
}
string json = JsonConvert.SerializeObject(_hsProspectList);
await SendContact(json);
The function that communicates with the HubSpot API is as follows:
private Task SendContact(string JsonString)
{
return Task.Factory.StartNew(() =>
{
string hapiKey = _userProfile.GetHapiKey();
var client = new RestClient(https://api.hubapi.com/);
var request = new RestRequest("contacts/v1/contact/batch/", Method.POST);
request.AddQueryParameter("hapikey", hapiKey);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(JsonString);
IRestResponse response = client.Execute<HubSpotProspect>(request);
var content = response.Content;
//Console.WriteLine("RESPONSE " + content);
});
}

Jackson: JSON parsing for array of parent elements : Root name '' does not match expected ('List')

I am getting the following exception after writing the below code.
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Root name 'Filing' does not match expected ('List') for type [collection type; class java.util.List, contains [simple type, class MasMonthlyReportDetail]]
JSON Object
{
"Filing":
[
{
"periodInfo":
{
"date": "06-05-2013",
"year": "2015",
"Month": "January"
},
"employerInfo":
{
"name": "Y",
"place": "Y",
"country": "N",
},
"employeeInfo":
[
{
"name": "785-23-0370",
"dob": "05/25/1952",
}
],
"messages":
[
{
"defaultMessage" : "xx",
"messageType" : "yy",
"messageCode" : "102"
}
]
},
{
"periodInfo":
{
"date": "06-05-2013",
"year": "2015",
"Month": "January"
},
"employerInfo":
{
"name": "Y",
"place": "Y",
"country": "N",
},
"employeeInfo":
[
{
"name": "785-23-0370",
"dob": "05/25/1952",
}
],
"messages":
[
{
"defaultMessage" : "xx",
"messageType" : "yy",
"messageCode" : "102"
}
]
}
]
}
Main Class
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
List<MasMonthlyReportDetail> lcd = objectMapper.readValue(new File(filePath),new TypeReference<List<MasMonthlyReportDetail>>(){});
MasMonthlyReportDetail.java
#JsonRootName(value="Filing")
public class MasMonthlyReportDetail {
private PeriodInfo periodInfo;
private EmployerInfo employerInfo;
List<EmployeeInfo> employeeInfo;
List<Messages> messages;
public PeriodInfo getPeriodInfo() {
return periodInfo;
}
public void setPeriodInfo(PeriodInfo periodInfo) {
this.periodInfo = periodInfo;
}
public EmployerInfo getEmployerInfo() {
return employerInfo;
}
public void setEmployerInfo(EmployerInfo employerInfo) {
this.employerInfo = employerInfo;
}
public List<EmployeeInfo> getEmployeeInfo() {
return employeeInfo;
}
public void setEmployeeInfo(List<EmployeeInfo> employeeInfo) {
this.employeeInfo = employeeInfo;
}
public List<Messages> getMessages() {
return messages;
}
public void setMessages(List<Messages> messages) {
this.messages = messages;
}
}
I made the following changes and the code worked for me.
Main Class:
InputStream inputStream = resource.getInputStream();
ObjectMapper objectMapper = new ObjectMapper();
MasMonthlyReportDetailHolder masMonthlyReportDetailHolder = objectMapper.readValue(inputStream, MasMonthlyReportDetailHolder.class);
List<MasMonthlyReportDetail> masMonthlyReportDetail = masMonthlyReportDetailHolder.getMasMonthlyReportDetail();
MasMonthlyReportDetailHolder class:
public class MasMonthlyReportDetailHolder {
private List<MasMonthlyReportDetail> masMonthlyReportDetail;
#JsonProperty("Filing")
public List<MasMonthlyReportDetail> getMasMonthlyReportDetail() {
return masMonthlyReportDetail;
}
public void setMasMonthlyReportDetail(
List<MasMonthlyReportDetail> masMonthlyReportDetail) {
this.masMonthlyReportDetail = masMonthlyReportDetail;
}
}
Adding #JsonProperty("Filing") is the key to avoid this issue. In case of any other procedure, do let me know.
have u tried this ?
jacksonObjectMapper.reader(MasMonthlyReportDetail.class).withRootName("Filing").readValue(jsonAsString);

How to parse JSON to List with Maps in Gson?

I have the following Java Classes:
public class ModuleParsed {
String id_component;
String id_instance;
Map<ModuleParam, ModuleParam> input;
Map<ModuleParam, List<ModuleParam>> output;
int id_paas;
}
and
public class ModuleParam {
String name;
Object type;
}
what should be the JSON expected to parse it as a List<ModuleParsed>?
listModules = gson.fromJson(br, new TypeToken<List<ModuleParsed>>() {}.getType());
Everything was ok until I introduced the input and output parameters.
EDIT
By doing the reverse process I have found the JSON should be something like
[
{
"id_component": "mod1",
"id_instance": "mod1_inst1",
"input": {
"moduleParam": {
"name": "param3",
"type": "obj3"
},
"moduleParam": {
"name": "param2",
"type": "obj2"
}
},
"id_paas": 1
},
{
"id_component": "mod2",
"id_instance": "mod2_inst1",
"input": {
"moduleParam": {
"name": "param3",
"type": "obj3"
},
"moduleParam": {
"name": "param2",
"type": "obj2"
}
},
"id_paas": 1
}
]
where the moduleParam elements were something like: parser.ModuleParam#36c51089
No matter how I name these elements I get the following error:
Exception in thread "main" com.google.gson.JsonParseException: Expecting object found: "moduleParam"
How can I obtain the class ModuleParsed with Gson?
Following #Brian's comment I realized I had no need to use complex objects as keys so this was my solution.
public class ModuleParsed {
String id_component;
String id_instance;
Map<String, ModuleParam> input;
Map<String, List<ModuleParam>> output;
int id_paas;
}
public class ModuleParam {
String name;
String id_module;
String id_instance;
}
for which I built the following JSON
[
{
"id_component": "mod1",
"id_instance": "mod1_inst1",
"input": {
"input1": {}
},
"output": {
"output1": [
{
"name": "input1",
"id_module": "mod2",
"id_instance": "mod2_inst1",
"type": "paramType"
},
{
"name": "input2",
"id_module": "mod2",
"id_instance": "mod2_inst1",
"type": "paramType"
}
],
"output2": []
},
"id_paas": 1
},
{
"id_component": "mod2",
"id_instance": "mod2_inst1",
"input": {
"input1": {
"name": "output1",
"id_module": "mod1",
"id_instance": "mod1_inst1",
"type": "paramType"
},
"input2": {
"name": "output1",
"id_module": "mod1",
"id_instance": "mod1_inst1",
"type": "paramType"
}
},
"output": {},
"id_paas": 1
}
]
The JSON was parsed correctly this time.