Get information from a json string? - c#

I have received a json string and i need help mapping that to an object
currently i am using:
string request = webClient.DownloadString(url);
which returns a json string of invoices:
"{\"invoices\":[
{\"url\":\"https://api.freeagent.com/v2/invoices/0000001\",\"contact\":\"https://api.freeagent.com/v2/contacts/000001\",\"dated_on\":\"2010-10-29\",\"due_on\":\"2010-11-28\",\"reference\":\"0001\",\"currency\":\"GBP\",\"exchange_rate\":\"1.0\",\"net_value\":\"60.0\",\"sales_tax_value\":\"68.0\",\"total_value\":\"528.0\",\"paid_value\":\"528.0\",\"due_value\":\"0.0\",\"status\":\"Paid\",\"omit_header\":false,\"payment_terms_in_days\":30,\"paid_on\":\"2011-11-14\"},{\"url\":\"https://api.freeagent.com/v2/invoices/0000002\",\"contact\":\"https://api.freeagent.com/v2/contacts/000002\",\"dated_on\":\"2010-11-19\",\"due_on\":\"2010-12-19\",\"reference\":\"0002\",\"currency\":\"GBP\",\"exchange_rate\":\"1.0\",\"net_value\":\"80.0\",\"sales_tax_value\":\"6.5\",\"total_value\":\"326.5\",\"paid_value\":\"650.0\",\"due_value\":\"76.5\",\"status\":\"Overdue\",\"comments\":\"Work\",\"omit_header\":false,\"payment_terms_in_days\":30}]}"
I have an invoice class:
public class Invoices
{
public string url { get; set; }
public string project { get; set; } //--
public string contact { get; set; } //--
public string dated_on { get; set; } //--
public string due_on { get; set; } //--
public string paid_on { get; set; }
public string reference { get; set; } //--
public string currency { get; set; } //--
public string exchange_rate { get; set; } //--
public string net_value { get; set; }
public string sales_tax_value { get; set; }
public string total_value { get; set; }
public string paid_value { get; set; }
public string due_value { get; set; }
public string discount_percent { get; set; }
public string status { get; set; }
public string comments { get; set; } //--
public string omit_header { get; set; }
public string payment_terms_in_days { get; set; } //--
public string ec_status { get; set; } //need to add fields
public string written_off_date { get; set; }
}
Different invoices can return different information which is why there is a lot of values in the class that may not be in the json string.
I have tried these approaches but keep getting errors:
List<Invoices> list = JsonConvert.DeserializeObject<List<Invoices>>(request);
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(request);
Could someone show me how to get the information shown in the string out?
Edit:
I have also tried:
var info = JsonConvert.DeserializeObject(request);
And that return this as a jObect
{
"invoices": [
{
"url": "https://api.freeagent.com/v2/invoices/000000",
"contact": "https://api.freeagent.com/v2/contacts/000000",
"dated_on": "2010-10-29",
"due_on": "2010-11-28",
"reference": "0000",
"currency": "GBP",
"exchange_rate": "1.0",
"net_value": "960.0",
"sales_tax_value": "568.0",
"total_value": "528.0",
"paid_value": "528.0",
"due_value": "0.0",
"status": "Paid",
"omit_header": false,
"payment_terms_in_days": 30,
"paid_on": "2011-11-14"
},
{
"url": "https://api.freeagent.com/v2/invoices/000000",
"contact": "https://api.freeagent.com/v2/contacts/000000",
"dated_on": "2010-11-19",
"due_on": "2010-12-19",
"reference": "0000",
"currency": "GBP",
"exchange_rate": "1.0",
"net_value": "980.0",
"sales_tax_value": "46.5",
"total_value": "326.5",
"paid_value": "650.0",
"due_value": "76.5",
"status": "Overdue",
"comments": "Work",
"omit_header": false,
"payment_terms_in_days": 30
}
}

The classes (as for the Json u posted) should look like this:
public class Invoice
{
public string url { get; set; }
public string contact { get; set; }
public string dated_on { get; set; }
public string due_on { get; set; }
public string reference { get; set; }
public string currency { get; set; }
public string exchange_rate { get; set; }
public string net_value { get; set; }
public string sales_tax_value { get; set; }
public string total_value { get; set; }
public string paid_value { get; set; }
public string due_value { get; set; }
public string status { get; set; }
public bool omit_header { get; set; }
public int payment_terms_in_days { get; set; }
public string paid_on { get; set; }
public string comments { get; set; }
}
public class RootObject
{
public List<Invoice> invoices { get; set; }
}
And:
RootObject list = JsonConvert.DeserializeObject<RootObject>(request);
The RootObject object contains a list of invoices
Json: (there is a ] missing on your version, near the end of the Json to close the array)
{
"invoices": [
{
"url": "https://api.freeagent.com/v2/invoices/000000",
"contact": "https://api.freeagent.com/v2/contacts/000000",
"dated_on": "2010-10-29",
"due_on": "2010-11-28",
"reference": "0000",
"currency": "GBP",
"exchange_rate": "1.0",
"net_value": "960.0",
"sales_tax_value": "568.0",
"total_value": "528.0",
"paid_value": "528.0",
"due_value": "0.0",
"status": "Paid",
"omit_header": false,
"payment_terms_in_days": 30,
"paid_on": "2011-11-14"
},
{
"url": "https://api.freeagent.com/v2/invoices/000000",
"contact": "https://api.freeagent.com/v2/contacts/000000",
"dated_on": "2010-11-19",
"due_on": "2010-12-19",
"reference": "0000",
"currency": "GBP",
"exchange_rate": "1.0",
"net_value": "980.0",
"sales_tax_value": "46.5",
"total_value": "326.5",
"paid_value": "650.0",
"due_value": "76.5",
"status": "Overdue",
"comments": "Work",
"omit_header": false,
"payment_terms_in_days": 30
}]
}

Could someone show me how to get the information shown in the string
out?
You can do this (dynamic):
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
dynamic lst = oSerializer.Deserialize<dynamic>(request );
Console.WriteLine(lst["invoices"][0]["due_on"]); <--put here whatever you want.
Here for example , I read the value of the first item in array :

Related

Change values in a JSON file C#

I have this code. How do I change the values of the JSON objects in code.
"externalReference": "Integrator Reference",
"proposalType": "Private Individual",
"dealer": {
"dealerID": 9344
},
"financeDetails": {
"type": "HP",
"cashDeposit": 111,
"settlement": 11,
"partExchange": 22,
"term": 72,
"apr": 12.9,
"loanamount": 0.0,
"distanceSelling": true,
"vehicleAsset": {
"type": "Used",
"class": "Car",
"source": "UK",
"purpose": "Social",
"vrm": "string",
"dateOfRegistration": "16-10-2020",
"manufacturer": "string",
"model": "string",
"derivative": "string",
"capCode": "ALGU21S164SDTA",
"CurrentMileage": 25000,
"vatRate": 20,
"netValue": 5000
},
"additionalAssets": [
{
"type": "MOT",
"netValue": 250,
"vatRate": 20,
"description": "string"
},
{
"type": "BCI_VAT",
"netValue": 350,
"vatRate": 5,
"description": "string"
}
]
},
I have this so far;
public static void CallRequest(string fieldName, string enteredFieldValue)
{
string sendProposalRequestSuccess = File.ReadAllText(sendProposalUnityJSONFile);
dynamic jsonObj = JsonConvert.DeserializeObject(sendProposalRequestSuccess);
jsonObj[fieldName] = enteredFieldValue;
string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
File.WriteAllText(sendProposalUnityJSONFile, output);
}
You can use JObject which has a method to parse json text you read from file to json objects. You can then access property using keys depending on the depth of the property.
1) JObject Parsing and Modification
string sendProposalRequestSuccess = File.ReadAllText("myjson.json");
JObject jsonObj = JObject.Parse(sendProposalRequestSuccess);
jsonObj["proposalType"] = "Private Company";
jsonObj["financeDetails"]["cashDeposit"] = 213;
string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
File.WriteAllText("myjson2.json", output);
Demo Example:
https://dotnetfiddle.net/DZA5BI
2) Json to C# Classes:
Another approach is convert json to C# classes using this helpful online tool. You can then deserialize json object to main class MyJson. This way you can access each property field and modify at your will then save json back to file.
This is pretty useful if you want to save to database or show in a table and several other applications.
public class MyJson
{
public string externalReference { get; set; }
public string proposalType { get; set; }
public Dealer dealer { get; set; }
public FinanceDetails financeDetails { get; set; }
}
public class AdditionalAsset
{
public string type { get; set; }
public int netValue { get; set; }
public int vatRate { get; set; }
public string description { get; set; }
}
public class Dealer
{
public int dealerID { get; set; }
}
public class FinanceDetails
{
public string type { get; set; }
public int cashDeposit { get; set; }
public int settlement { get; set; }
public int partExchange { get; set; }
public int term { get; set; }
public double apr { get; set; }
public double loanamount { get; set; }
public bool distanceSelling { get; set; }
public VehicleAsset vehicleAsset { get; set; }
public List<AdditionalAsset> additionalAssets { get; set; }
}
public class VehicleAsset
{
public string type { get; set; }
public string #class { get; set; }
public string source { get; set; }
public string purpose { get; set; }
public string vrm { get; set; }
public string dateOfRegistration { get; set; }
public string manufacturer { get; set; }
public string model { get; set; }
public string derivative { get; set; }
public string capCode { get; set; }
public int CurrentMileage { get; set; }
public int vatRate { get; set; }
public int netValue { get; set; }
}
Implementation:
string sendProposalRequestSuccess = File.ReadAllText("myjson.json");
var jsonObj = JsonConvert.DeserializeObject<MyJson>(sendProposalRequestSuccess);
jsonObj.financeDetails.cashDeposit = 231;
string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
File.WriteAllText("myjson2.json", output);
Output:

Deserilizing Json Response of HttpClient using ASP.NET Core

I am calling a third-party API with HttpClient GET Request and it works fine. The response is quite complex of objects. All I want to do is to extract a specific attribute within these objects. Here is the response Json
"creationTime": "2021-11-06T12:22:49.602Z",
"currency": "USD",
"customer": {
"firstName": "xxxx"
},
"id": "xxxx",
"lastUpdatedTime": "2021-11-06T12:22:51.689Z",
"merchant": "xxx",
"merchantAmount": 33,
"merchantCategoryCode": "5311",
"merchantCurrency": "USD",
"reference": "XX",
"result": "SUCCESS",
"sourceOfFunds": {
"provided": {
"card": {
"brand": "MASTERCARD",
"expiry": {
"month": "X",
"year": "XX"
},
"fundingMethod": "DEBIT",
"nameOnCard": "XXX",
"number": "XXXXX123",
"scheme": "MASTERCARD",
"storedOnFile": "NOT_STORED"
}
},
"type": "CARD"
},
"status": "CAPTURED",
"totalAuthorizedAmount": 33,
"totalCapturedAmount": 33,
"totalRefundedAmount": 0,
"transaction": [
{
"3DSecure": {
"acsEci": "02",
"authenticationToken": "XXXX+XXXX=",
"paResStatus": "Y",
"veResEnrolled": "Y",
"xid": "mmmXXX"
},
"3DSecureId": "XXX",
"authorizationResponse": {
"cardSecurityCodeError": "M",
"commercialCardIndicator": "1",
"date": "1106",
"financialNetworkCode": "XX",
"financialNetworkDate": "2021-11-06",
"posData": "XXX",
"posEntryMode": "xxx",
"processingCode": "000000",
"responseCode": "00",
"stan": "22443",
"time": "122249",
"transactionIdentifier": "014VPH"
},
"customer": {
"firstName": "XXXX"
},
"device": {
},
"gatewayEntryPoint": "CHECKOUT",
"merchant": "XXXX",
"order": {
"amount": 33,
"chargeback": {
"amount": 0,
"currency": "USD"
},
"creationTime": "2021-11-06T12:22:49.602Z",
"currency": "USD",
"description": "243",
"id": "xxxxx",
"lastUpdatedTime": "2021-11-06T12:22:51.689Z",
"merchantAmount": 33,
"merchantCategoryCode": "xxx",
"merchantCurrency": "IQD",
"reference": "243",
"status": "CAPTURED",
"totalAuthorizedAmount": 33,
"totalCapturedAmount": 33,
"totalRefundedAmount": 0
},
"response": {
"acquirerCode": "00",
"acquirerMessage": "Approved",
"cardSecurityCode": {
"acquirerCode": "M",
"gatewayCode": "MATCH"
},
"gatewayCode": "APPROVED"
},
"result": "SUCCESS",
"sourceOfFunds": {
"provided": {
"card": {
"brand": "MASTERCARD",
"expiry": {
"month": "x",
"year": "xx"
},
"fundingMethod": "DEBIT",
"nameOnCard": "xxxxx",
"number": "xxxxxx",
"scheme": "MASTERCARD",
"storedOnFile": "NOT_STORED"
}
},
"type": "CARD"
},
"timeOfLastUpdate": "2021-11-06T12:22:51.689Z",
"timeOfRecord": "2021-11-06T12:22:49.617Z",
}
]
}
I'd like to extract "status": "CAPTURED" and "acquirerCode": "00" . here is what I tried
var client = new HttpClient();
string _ContentType = "application/json";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64EncodedAuthenticationString);
var _UserAgent = "d-fens HttpClient";
client.DefaultRequestHeaders.Add("User-Agent", _UserAgent);
HttpResponseMessage response;
response = await client.GetAsync(api_URL);
var resContent = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
var content = response.Content.ReadAsStringAsync().Result;
return Ok(resContent);
Extracting these values would solve the issue I'm facing. Thanks in advance
if you need just this 2 values the easiest way is
var json = response.Content.ReadAsStringAsync().Result;
var result = JObject.Parse(json);
var status= result["status"];
var acquirerCode= result["transaction"][0]["response"]["acquirerCode"];
output
CAPTURED
00
And there is a hard way
var json = response.Content.ReadAsStringAsync().Result;
var jsonDeserialized=JsonConvert.DeserializeObject<Data>(json);
var status= jsonDeserialized.Status;
var acquirerCode=jsonDeserialized.Transaction.Select(t => t.Response.AcquirerCode).FirstOrDefault();
classes
public partial class Data
{
[JsonProperty("creationTime")]
public DateTimeOffset CreationTime { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("customer")]
public Customer Customer { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("lastUpdatedTime")]
public DateTimeOffset LastUpdatedTime { get; set; }
[JsonProperty("merchant")]
public string Merchant { get; set; }
[JsonProperty("merchantAmount")]
public long MerchantAmount { get; set; }
[JsonProperty("merchantCategoryCode")]
public long MerchantCategoryCode { get; set; }
[JsonProperty("merchantCurrency")]
public string MerchantCurrency { get; set; }
[JsonProperty("reference")]
public string Reference { get; set; }
[JsonProperty("result")]
public string Result { get; set; }
[JsonProperty("sourceOfFunds")]
public SourceOfFunds SourceOfFunds { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("totalAuthorizedAmount")]
public long TotalAuthorizedAmount { get; set; }
[JsonProperty("totalCapturedAmount")]
public long TotalCapturedAmount { get; set; }
[JsonProperty("totalRefundedAmount")]
public long TotalRefundedAmount { get; set; }
[JsonProperty("transaction")]
public Transaction[] Transaction { get; set; }
}
public partial class Customer
{
[JsonProperty("firstName")]
public string FirstName { get; set; }
}
public partial class SourceOfFunds
{
[JsonProperty("provided")]
public Provided Provided { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
}
public partial class Provided
{
[JsonProperty("card")]
public Card Card { get; set; }
}
public partial class Card
{
[JsonProperty("brand")]
public string Brand { get; set; }
[JsonProperty("expiry")]
public Expiry Expiry { get; set; }
[JsonProperty("fundingMethod")]
public string FundingMethod { get; set; }
[JsonProperty("nameOnCard")]
public string NameOnCard { get; set; }
[JsonProperty("number")]
public string Number { get; set; }
[JsonProperty("scheme")]
public string Scheme { get; set; }
[JsonProperty("storedOnFile")]
public string StoredOnFile { get; set; }
}
public partial class Expiry
{
[JsonProperty("month")]
public string Month { get; set; }
[JsonProperty("year")]
public string Year { get; set; }
}
public partial class Transaction
{
[JsonProperty("3DSecure")]
public The3DSecure The3DSecure { get; set; }
[JsonProperty("3DSecureId")]
public string The3DSecureId { get; set; }
[JsonProperty("authorizationResponse")]
public AuthorizationResponse AuthorizationResponse { get; set; }
[JsonProperty("customer")]
public Customer Customer { get; set; }
[JsonProperty("device")]
public Device Device { get; set; }
[JsonProperty("gatewayEntryPoint")]
public string GatewayEntryPoint { get; set; }
[JsonProperty("merchant")]
public string Merchant { get; set; }
[JsonProperty("order")]
public Order Order { get; set; }
[JsonProperty("response")]
public Response Response { get; set; }
[JsonProperty("result")]
public string Result { get; set; }
[JsonProperty("sourceOfFunds")]
public SourceOfFunds SourceOfFunds { get; set; }
[JsonProperty("timeOfLastUpdate")]
public DateTimeOffset TimeOfLastUpdate { get; set; }
[JsonProperty("timeOfRecord")]
public DateTimeOffset TimeOfRecord { get; set; }
}
public partial class AuthorizationResponse
{
[JsonProperty("cardSecurityCodeError")]
public string CardSecurityCodeError { get; set; }
[JsonProperty("commercialCardIndicator")]
public long CommercialCardIndicator { get; set; }
[JsonProperty("date")]
public long Date { get; set; }
[JsonProperty("financialNetworkCode")]
public string FinancialNetworkCode { get; set; }
[JsonProperty("financialNetworkDate")]
public DateTimeOffset FinancialNetworkDate { get; set; }
[JsonProperty("posData")]
public string PosData { get; set; }
[JsonProperty("posEntryMode")]
public string PosEntryMode { get; set; }
[JsonProperty("processingCode")]
public string ProcessingCode { get; set; }
[JsonProperty("responseCode")]
public string ResponseCode { get; set; }
[JsonProperty("stan")]
public long Stan { get; set; }
[JsonProperty("time")]
public long Time { get; set; }
[JsonProperty("transactionIdentifier")]
public string TransactionIdentifier { get; set; }
}
public partial class Device
{
}
public partial class Order
{
[JsonProperty("amount")]
public long Amount { get; set; }
[JsonProperty("chargeback")]
public Chargeback Chargeback { get; set; }
[JsonProperty("creationTime")]
public DateTimeOffset CreationTime { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("description")]
public long Description { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("lastUpdatedTime")]
public DateTimeOffset LastUpdatedTime { get; set; }
[JsonProperty("merchantAmount")]
public long MerchantAmount { get; set; }
[JsonProperty("merchantCategoryCode")]
public string MerchantCategoryCode { get; set; }
[JsonProperty("merchantCurrency")]
public string MerchantCurrency { get; set; }
[JsonProperty("reference")]
public long Reference { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("totalAuthorizedAmount")]
public long TotalAuthorizedAmount { get; set; }
[JsonProperty("totalCapturedAmount")]
public long TotalCapturedAmount { get; set; }
[JsonProperty("totalRefundedAmount")]
public long TotalRefundedAmount { get; set; }
}
public partial class Chargeback
{
[JsonProperty("amount")]
public long Amount { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
}
public partial class Response
{
[JsonProperty("acquirerCode")]
public string AcquirerCode { get; set; }
[JsonProperty("acquirerMessage")]
public string AcquirerMessage { get; set; }
[JsonProperty("cardSecurityCode")]
public CardSecurityCode CardSecurityCode { get; set; }
[JsonProperty("gatewayCode")]
public string GatewayCode { get; set; }
}
public partial class CardSecurityCode
{
[JsonProperty("acquirerCode")]
public string AcquirerCode { get; set; }
[JsonProperty("gatewayCode")]
public string GatewayCode { get; set; }
}
public partial class The3DSecure
{
[JsonProperty("acsEci")]
public string AcsEci { get; set; }
[JsonProperty("authenticationToken")]
public string AuthenticationToken { get; set; }
[JsonProperty("paResStatus")]
public string PaResStatus { get; set; }
[JsonProperty("veResEnrolled")]
public string VeResEnrolled { get; set; }
[JsonProperty("xid")]
public string Xid { get; set; }
}

Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value

I have a Json Model Schema from a third party API that looks like this:
{
"Entries": [
{
"Id": "",
"RowId": 0,
"FormId": "",
"FormExternalId": "",
"FormVersion": 0,
"DeviceId": "",
"UserFirstName": "",
"UserLastName": "",
"UserEmail": "",
"UserExternalId": "",
"Latitude": 0,
"Longitude": 0,
"StartTime": "Date",
"CompleteTime": "Date",
"ReceivedTime": "Date",
"AnswerFormat": "",
"Answers": [
{
"Name": "",
"Type": "",
"Value": "",
"Answers": [
"Answer_GET_"
]
}
],
"AnswersFlat": "Array[AnswerSet]",
"AnswersFlatXml": "XML",
"AnswersRawXml": "XML",
"AnswersRawJson": "JSON",
"TaskId": "",
"DSRowId": "",
"MediaAsUrl": false,
"Fields": "",
"PurgeDays": 0,
"CompanyId": 0
}
],
"TotalRows": 0,
"ResponseStatus": {
"ErrorCode": "",
"Message": "",
"Errors": [
{
"ErrorCode": "",
"FieldName": "",
"Message": ""
}
]
}
}
I made a class for this in Visual Studio that looks like this:
class form_results
{
public class Rootobject
{
public Entry[] Entries { get; set; }
public int TotalRows { get; set; }
public Responsestatus ResponseStatus { get; set; }
}
public class Responsestatus
{
public string ErrorCode { get; set; }
public string Message { get; set; }
public Error[] Errors { get; set; }
}
public class Error
{
public string ErrorCode { get; set; }
public string FieldName { get; set; }
public string Message { get; set; }
}
public class Entry
{
public string Id { get; set; }
public int RowId { get; set; }
public string FormId { get; set; }
public string FormExternalId { get; set; }
public int FormVersion { get; set; }
public string DeviceId { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserEmail { get; set; }
public string UserExternalId { get; set; }
public float Latitude { get; set; }
public float Longitude { get; set; }
public string StartTime { get; set; }
public string CompleteTime { get; set; }
public string ReceivedTime { get; set; }
public string AnswerFormat { get; set; }
public Answer[] Answers { get; set; }
public string AnswersFlat { get; set; }
public string AnswersFlatXml { get; set; }
public string AnswersRawXml { get; set; }
public string AnswersRawJson { get; set; }
public string TaskId { get; set; }
public string DSRowId { get; set; }
public bool MediaAsUrl { get; set; }
public string Fields { get; set; }
public int PurgeDays { get; set; }
public int CompanyId { get; set; }
}
public class Answer
{
public string Name { get; set; }
public string Type { get; set; }
public string Value { get; set; }
public string[] Answers { get; set; }
}
}
When I try to deserialize the json with the following command:
var parsedJson = JsonConvert.DeserializeObject<form_results.Rootobject>(json);
I'm geting the error "Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: {. Path 'Entries[0].Answers[0].Answers', line 25, position 25.'"
That part of the Json string looks like this:
{... more json results...
"AnswerFormat": "Rich",
"Answers": [{
"Name": "Page 1",
"Type": "Group",
"Answers": [{
"Name": "Value 1",
"Type": "SelectOne"
},
{
"Name": "Value 2",
"Type": "SelectOne"
}
]
}]
}
]
The Json is valid, so that is not the problem. As far as I can see the problem occurs at the array section of the Json file.
Also tried var parsedJson = JsonConvert.DeserializeObject <List<form_results.Rootobject>>(json); but gave also an error.
What I want is the results (answers) from the Answers array.
Your Answer class is declared like this
public class Answer
{
public string Name { get; set; }
public string Type { get; set; }
public string Value { get; set; }
public string[] Answers { get; set; }
}
This includes an array of string called Answers
But in your JSON, this array is an array of objects (Extract below)
"Answers": [{
"Name": "Value 1",
"Type": "SelectOne"
},
{
"Name": "Value 2",
"Type": "SelectOne"
}
]
So you need to change your class to match this JSON. Maybe like this
public class Answer
{
public string Name { get; set; }
public string Type { get; set; }
public string Value { get; set; }
public SubAnswer[] Answers { get; set; }
}
public class SubAnswer
{
public string Name { get; set; }
public string Type { get; set; }
}
Or you could maybe use the Composite pattern, if you want Answer and SubAnswer to be the same.
It looks like the class answers can contain further answers thats why you can modify your Answer class like following:
public class Answer
{
public string Name { get; set; }
public string Type { get; set; }
public string Value { get; set; }
public List<Answer> Answers { get; set; }
}

JSON deserialization is not working in Web API

I want to deserialize a json request but it is not working in Web API. My code is below for the deserialization. Can you please tell me what I am doing wrong?
[HttpPost]
public HttpResponseMessage AddOrder(string username , string password, JObject jsonResult)
{
try
{
AuthRepository _auth = new AuthRepository();
OrderDTO.RootObject O = new OrderDTO.RootObject();
O = JsonConvert.DeserializeObject<OrderDTO.RootObject>(jsonResult.ToString());
}
catch (Exception ex)
{
return Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, ex);
}
}
This is the JSON that will received by our method:
{
"token": "D8xJD2CI6PrkB3q5gnlT",
"shipment": {
"hawb": "0800780108",
"service_level": "CURBSIDE",
"status": "NEW",
"description": "bundle of things",
"service_level_code": "CB",
"delivery_date": "8/22/2019 5:01:00 PM",
"delivery2_date": "8/22/2019 12:00:00 AM",
"origin": {
"name": "ESTES EXPRESS BOSTON-080",
"nbr": "0800780108",
"phone": "508-513-0120",
"email": "",
"address1": "215 BODWELL ST",
"city": "AVON",
"state": "MA",
"zip_postal_code": "02322",
"country": "US"
},
"dest": {
"name": "JOSEPH VINOGRAD",
"nbr": "",
"phone": "",
"email": "",
"address1": "14 CORTLAND DR",
"city": "Sharon",
"state": "MA",
"zip_postal_code": "02067",
"country": "US"
},
"piece_count": "2",
"dangerous_goods": "0",
"weight": 190
}
}
Code for class
public class OrderDTO
{
public class Origin
{
public string name { get; set; }
public string nbr { get; set; }
public string phone { get; set; }
public string email { get; set; }
public string address1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip_postal_code { get; set; }
public string country { get; set; }
}
public class Dest
{
public string name { get; set; }
public string nbr { get; set; }
public string phone { get; set; }
public string email { get; set; }
public string address1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip_postal_code { get; set; }
public string country { get; set; }
}
public class Shipment
{
public string hawb { get; set; }
public string service_level { get; set; }
public string status { get; set; }
public string description { get; set; }
public string service_level_code { get; set; }
public string delivery_date { get; set; }
public string delivery2_date { get; set; }
public Origin origin { get; set; }
public Dest dest { get; set; }
public string piece_count { get; set; }
public string dangerous_goods { get; set; }
public double weight { get; set; }
}
public class RootObject
{
public string token { get; set; }
public Shipment shipment { get; set; }
}
}
You can add username and password to your OrderDTO class (or another class containing these three objects) and then change action definition like:
public HttpResponseMessage AddOrder(OrderDRO input).
Then you don't need to use json serialization and easily you can do your logic.

JSON to C# classes Issue

I am fairly new to working with JSON and I have a bit of an issue with a JSON response I am getting from a web service. I've tried a bunch of online "JSON to c# class" generators and none of them seem to work with this specific bit of JSON. I am working with the Pocket API and the response I get below. Can anyone point me in the right direction for formatting this in to classes?
{
"status": 1,
"list": {
"229279689": {
"item_id": "229279689",
"resolved_id": "229279689",
"given_url": "http://www.grantland.com/blog/the-triangle/post/_/id/38347/ryder-cup- preview",
"given_title": "The Massive Ryder Cup Preview - The Triangle Blog - Grantland",
"favorite": "0",
"status": "0",
"resolved_title": "The Massive Ryder Cup Preview",
"resolved_url": "http://www.grantland.com/blog/the-triangle/post/_/id/38347/ryder-cup-preview",
"excerpt": "The list of things I love about the Ryder Cup is so long that it could fill a (tedious) novel, and golf fans can probably guess most of them.",
"is_article": "1",
"has_video": "1",
"has_image": "1",
"word_count": "3197",
"images": {
"1": {
"item_id": "229279689",
"image_id": "1",
"src": "http://a.espncdn.com/combiner/i?img=/photo/2012/0927/grant_g_ryder_cr_640.jpg&w=640&h=360",
"width": "0",
"height": "0",
"credit": "Jamie Squire/Getty Images",
"caption": ""
}
},
"videos": {
"1": {
"item_id": "229279689",
"video_id": "1",
"src": "http://www.youtube.com/v/Er34PbFkVGk?version=3&hl=en_US&rel=0",
"width": "420",
"height": "315",
"type": "1",
"vid": "Er34PbFkVGk"
}
}
}
}
}
Thanks for any pointers,
A little bit tricky, but this should work. ( Because of the property names like 229279689)
var result = JsonConvert.DeserializeObject<Root>(json);
public class MyImage
{
public string item_id { get; set; }
public string image_id { get; set; }
public string src { get; set; }
public string width { get; set; }
public string height { get; set; }
public string credit { get; set; }
public string caption { get; set; }
}
public class MyVideo
{
public string item_id { get; set; }
public string video_id { get; set; }
public string src { get; set; }
public string width { get; set; }
public string height { get; set; }
public string type { get; set; }
public string vid { get; set; }
}
public class MyListItem
{
public string item_id { get; set; }
public string resolved_id { get; set; }
public string given_url { get; set; }
public string given_title { get; set; }
public string favorite { get; set; }
public string status { get; set; }
public string resolved_title { get; set; }
public string resolved_url { get; set; }
public string excerpt { get; set; }
public string is_article { get; set; }
public string has_video { get; set; }
public string has_image { get; set; }
public string word_count { get; set; }
public Dictionary<string, MyImage> images; // <---
public Dictionary<string, MyVideo> videos; // <---
}
public class Root
{
public int status;
public Dictionary<string, MyListItem> list; // <---
}
Did you try Json.NET:
JObject o = JObject.Parse("some json");
string name = (string)o["Name"];

Categories

Resources