HubSpot API POST contacts in batches - json

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);
});
}

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; }
}
}

Json.net append json file

I have the following code which uses Json.net:
class HistorianRecord
{
public string tagname { get; set; }
public string engunits { get; set; }
public string value { get; set; }
public string quality { get; set; }
public DateTime timestamp { get; set; }
}
private static void createJSONFile(DataTable dt)
{
var HistorianData = new List<HistorianRecord>();
foreach(DataRow row in dt.Rows)
{
HistorianData.Add(new HistorianRecord()
{
tagname = row["tagname"].ToString(),
engunits = row["engunits"].ToString(),
value = row["value"].ToString(),
quality = row["quality"].ToString(),
timestamp = DateTime.Parse(row["timestamp"].ToString())
});
}
var serializer = new JavaScriptSerializer();
var serializedResult = serializer.Serialize(HistorianData);
var deserializedResult = serializer.Deserialize<List<HistorianRecord>>(serializedResult);
File.WriteAllText(folderPath + fileName, JsonConvert.SerializeObject(deserializedResult));
}
Which produces the following JSON file, which I have shortened for this post as the are > 1000 rows in the datatable:
[
{
"tagname": "mytag1",
"engunits": "",
"value": "2",
"quality": "Good NonSpecific",
"timestamp": "2018-12-13T10:45:05Z"
},
{
"tagname": "myTag2",
"engunits": "",
"value": "0",
"quality": "Good NonSpecific",
"timestamp": "2018-12-13T10:45:00Z"
}
]
I would like to amend my code to so I can add some items at the beginning of the JSON file so it looks more like this:
[
{
"name": "ARandomName",
"content": [
{
"tagname": "mytag1",
"engunits": "",
"value": "2",
"quality": "Good NonSpecific",
"timestamp": "2018-12-13T10:45:05Z"
},
{
"tagname": "myTag2",
"engunits": "",
"value": "0",
"quality": "Good NonSpecific",
"timestamp": "2018-12-13T10:45:00Z"
}
]
}
]
This is so I can create some documents for a test MongoDB installation that I am investigating so all help is appreciated.
You simply can wrap your deserialized list of HistorianRecords in an anonymous object and reserialize it:
var anon = new
{
name = "ARandomName",
content = deserializedResult
};
string newJson = JsonConvert.SerializeObject(anon, Formatting.Indented);
Fiddle: https://dotnetfiddle.net/6kSvxS

NewtonSoft JSON does not parse referenced items in an array

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.

Json data reading

I have following json format data reading problem
I tried this code which is not working because Answer node have Answer named data
string filePath = Server.MapPath("../App_Data/history.txt");
using (StreamReader r = new StreamReader(filePath))
{
string json = r.ReadToEnd();
List<RootObject> Questions =
JsonConvert.DeserializeObject<List<RootObject>>(json);
public class Answer
{
public string Answer { get; set; }
}
public class Question
{
public string Question { get; set; }
public int CorrectAnswer { get; set; }
public List<Answer> Answers { get; set; }
}
public class RootObject
{
public List<Question> Questions { get; set; }
}
JSON Data :
{
"Questions": [
{
"Question": "Who was the Chola King who brought Ganga from North to South?",
"CorrectAnswer": 1 ,
"Answers": [
{
"Answer": "Raja Raja Chola"
},
{
"Answer": "Rajendra Chola"
},
{
"Answer": "Parantaka"
},
{
"Answer": "Mahendra"
}
]
},
{
"Question": "The writ of 'Habeas Corpus' is issued in the event of:",
"CorrectAnswer": 2 ,
"Answers": [
{
"Answer": "Loss of Property"
},
{
"Answer": "Refund of Excess Taxes"
},
{
"Answer": "Wrongful Police Detention"
},
{
"Answer": "Violation of the Freedom of Speech"
}
]
}
]}

How to write a linq query or use a storedprocedure to build a json object in MVC4?

Hi all i have a Database where i have some tables named
[Options],[ProductAttributes],[Products],[ProductSKU],[ProductSKUOptionMappings]
i had added this as entity model to my project,now i want to write a linq query for this where i can get these column from the above specified tables
based on this stored procedure
ALTER procedure [dbo].[GetProductDetail]
(
#ProductID bigint
)
as
begin
Select P.ProductName, P.ProductDescription, PA.SKU, PA.OptionId,O.OptionName, PA.Value, PS.ImageURL from ProductSKU PS
INNER JOIN ProductAttributes PA ON PS.SKU = PA.SKU
INNER JOIN Products P ON P.ProductId = PS.ProductId
INNER JOIN Options O ON O.OptionsId = PA.OptionId
WHERE PS.ProductId = #ProductID
end
i want to convert this query into linq query or use this as Storedprocedure to get my required Json object
the output of my stored procedure looks like this
ProductName ProductDescription SKU OptionId OptionName Value ImageURL
Tactical Long Sleeve Shirts Hemline side slits Shirt_1001 1 Color Grey C:\Users\Administrator\Desktop\Images\LongSleeveShirt.jpg
Tactical Long Sleeve Shirts Hemline side slits Shirt_1001 2 Size S C:\Users\Administrator\Desktop\Images\LongSleeveShirt.jpg
Tactical Long Sleeve Shirts Hemline side slits Shirt_1001 3 Fit Regular C:\Users\Administrator\Desktop\Images\LongSleeveShirt.jpg
each product may have different SKUs like the above so can any one help me here how can i build my json object which looks like this
i want my json object to be in this format
var productdetails={
"productId": "1",
"productname": "Casualshirts",
"productSkus": [
{
"Skuimage": "URL",
"SKU": [
{
"ProducSKU": "Shoe1001",
"Options": [
{
"productOptions": [
{
"OptionID": "1",
"optionname": "Color",
"value": "Black"
},
{
"OptionID": "2",
"optionname": "Size",
"value": "S"
},
{
"OptionID": "3",
"optionname": "Fit",
"value": "Regular"
}
]
}
]
},
{
"ProducSKU": "Shoe1002",
"Options": [
{
"productOptions": [
{
"OptionID": "1",
"optionname": "Color",
"value": "Black"
},
{
"OptionID": "2",
"optionname": "Size",
"value": "S"
},
{
"OptionID": "3",
"optionname": "Fit",
"value": "Regular"
}
]
}
]
},
{
"ProducSKU": "Shoe1003",
"Options": [
{
"productOptions": [
{
"OptionID": "1",
"optionname": "Color",
"value": "Black"
},
{
"OptionID": "2",
"optionname": "Size",
"value": "S"
},
{
"OptionID": "3",
"optionname": "Fit",
"value": "Regular"
}
]
}
]
}
]
and here is my model class
public class ProductItems
{
public long ProductID { get; set; }
public string ProductName { get; set; }
public string ImageURL { get; set; }
public List<productSKU> SKUs { get; set; }
}
public class productSKU
{
public string productsku { get; set;}
public string SKUImageURL { get; set;}
public List<options> oPTIONS { get; set; }
}
public class options
{
public long OptionID { get; set; }
public string OptionName { get; set;}
public string OptionValue { get; set;}
}
can any one help me in how to construct my stored procedure or linq query as above json pbjkect thanks in advance...
this is how i am trying to bind my data to my model
public IEnumerable<ProductItems> ProductDeatils(long ProductID)
{
var productdeatils = products.ExecuteStoreQuery<ProductItems>("GetProductDetail #ProductID ", new SqlParameter("#ProductID", ProductID));
var data=new List<ProductItems>();
foreach (var prod in productdeatils)
{
ProductItems items = new ProductItems();
items.ProductID = prod.ProductID;
items.ProductName = prod.ProductName;
items.SKUs
}
return data;
}
i am stuck with number of properties in my class and number of Database columns i amn retrieving from my procedure how can i map them to my model
Assuming you have retrieved an instance of your ProductItems model from your data layer you could project it into an anonymous object to be passed to a JsonResult in order to achieve the desired JSON structure:
public ActionResult SomeAction()
{
ProductItems model = ... retrieve the model from your data layer
var result = new
{
productId = model.ProductID,
productname = model.ProductName,
productSkus = model.SKUs.Select(sku => new
{
Skuimage = sku.SKUImageURL,
SKU = new[]
{
new
{
ProducSKU = sku.productsku,
Options = new[]
{
new
{
productOptions = sku.oPTIONS.Select(opt => new
{
OptionID = opt.OptionID,
optionname = opt.OptionName,
value = opt.OptionValue
})
}
}
}
}
})
};
return Json(result, JsonRequestBehavior.AllowGet);
}