JSON to C# classes Issue - c#

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"];

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:

Why is my inner array not being deserialized?

I have some JSON which I'd like to deserialize into Objects.
I'm trying to do it like this, but I only get some of the JSON deserialized and the vin and vout JSON are either 0s or nulls. What am I doing wrong?
Transaction t = JsonConvert.DeserializeObject<RPCResponse<Transaction>>(json).result;
JSON:
{
"result": {
"hex": "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d0104ffffffff0100f2052a0100000043410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac00000000",
"txid": "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098",
"hash": "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098",
"size": 134,
"version": 1,
"locktime": 0,
"vin": [
{
"coinbase": "04ffff001d0104",
"sequence": 4294967295
}
],
"vout": [
{
"value": 50.00000000,
"n": 0,
"scriptPubKey": {
"asm": "0496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858ee OP_CHECKSIG",
"hex": "410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac",
"reqSigs": 1,
"type": "pubkey",
"addresses": [
"12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX"
]
}
}
],
"blockhash": "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048",
"confirmations": 563356,
"time": 1231469665,
"blocktime": 1231469665
},
"error": null,
"id": "getrawtransaction"
}
The output in the debugger looks like this:
My Classes look like this:
public class RPCResponse<T>
{
public T result { get; set; }
public string error { get; set; }
public string id { get; set; }
}
public class Transaction
{
public string TxId { get; set; }
public long Size { get; set; }
public long Version { get; set; }
public long LockTime { get; set; }
public TransactionInputCoinbase[] Vin { get; set; }
public TransactionOutput[] Vout { get; set; }
public string BlockHash { get; set; }
public long Time { get; set; }
}
public class TransactionInputCoinbase
{
string Coinbase { get; set; }
string Sequence { get; set; }
}
public class TransactionOutput
{
decimal Value { get; set; }
int N { get; set; }
ScriptPubKey ScriptPubKey { get; set; }
}
public class ScriptPubKey
{
string Asm { get; set; }
string Hex { get; set; }
long ReqSigs { get; set; }
string Type { get; set; }
string[] Addresses { get; set; }
}
The lack of public properties on the said objects
For example
public class TransactionInputCoinbase
{
string Coinbase { get; set; } //<--NOT PUBLIC
string Sequence { get; set; } //<--NOT PUBLIC
}
means those properties will never be set when initialized via deserialization.
The same goes for TransactionOutput and ScriptPubKey based on the code originally provided.

How to parse JSON data by Json.net when there is a name of special name?

using (var client = new HttpClient())
{
HttpResponseMessage response = client.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
var rootResult = JsonConvert.DeserializeObject<LastFMResponse_ArtistTracks>(result);
return rootResult;
}
else
{
return null;
}
}
The above string result returns the full json response that looks something like
{
"artisttracks": {
"track": [
{
"artist": {
"#text": "Flying Lotus",
"mbid": "fc7376fe-1a6f-4414-b4a7-83f50ed59c92"
},
"name": "Arkestry",
"streamable": "0",
"mbid": "5f2c6783-f876-4bbe-9577-d3498da6b0ab",
"album": {
"#text": "Cosmogramma",
"mbid": "7369257e-2346-4fe6-8810-c92c409d6671"
},
"url": "https://www.last.fm/music/Flying+Lotus/_/Arkestry",
"image": [
{
"#text": "https://lastfm-img2.akamaized.net/i/u/34s/50227cde795b4702c7b4d7ddcf0b85ff.png",
"size": "small"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/64s/50227cde795b4702c7b4d7ddcf0b85ff.png",
"size": "medium"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/174s/50227cde795b4702c7b4d7ddcf0b85ff.png",
"size": "large"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/300x300/50227cde795b4702c7b4d7ddcf0b85ff.png",
"size": "extralarge"
}
],
"date": {
"uts": "1530728536",
"#text": "04 Jul 2018, 18:22"
}
However the DeserializeObject method is not able to deserialize the string into the object that holds a text field instead of the #text one.
The following is my class definition for the DeserializeObject destination.
public class LastFMResponse_ArtistTracks
{
public Artisttracks artisttracks { get; set; }
public class Artisttracks
{
public Track[] track { get; set; }
public Attr #attr { get; set; }
}
public class Attr
{
public string user { get; set; }
public string artist { get; set; }
public string page { get; set; }
public string perPage { get; set; }
public string totalPages { get; set; }
public string total { get; set; }
}
public class Track
{
public Artist artist { get; set; }
public string name { get; set; }
public string streamable { get; set; }
public string mbid { get; set; }
public Album album { get; set; }
public string url { get; set; }
public Image[] image { get; set; }
public Date date { get; set; }
}
public class Artist
{
public string text { get; set; }
public string mbid { get; set; }
}
public class Album
{
public string text { get; set; }
public string mbid { get; set; }
}
public class Date
{
public string uts { get; set; }
public string text { get; set; }
}
public class Image
{
public string text { get; set; }
public string size { get; set; }
}
}
Am I doing this the improper way or is there a way to get the text?
Because your JSON data name is #text, Default JSON Convert can't bind with public string text { get; set; } property
a simple way, you can try to add JsonProperty Attribute on public string text { get; set; }property.
[JsonProperty("#text")]
public string text { get; set; }
C# Demo
JsonPropertyAttribut

Deserializing result of steam storefront api using RestSharp always returns null

I've been trying to use the steam storefront api http://store.steampowered.com/api/.
The problem is that when I feed the result of the api to RestSharp, the data is always null.
So my question is how do I get the Rest call deserialized?
First, this is what you would be expecting when calling appdetails?appids=[appid]
{
"3400": {
"success": true,
"data": {
"type": "game",
"name": "Hammer Heads Deluxe",
"steam_appid": 3400,
"required_age": 0,
"is_free": false,
"detailed_description": "",
"about_the_game": "",
"short_description": "",
"supported_languages": "English",
"header_image": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/3400\/header.jpg?t=1447350883",
"website": null,
"pc_requirements": {
"minimum": "<p><strong>Minimum Requirements:<\/strong> Windows 98\/ME\/2000\/XP, 128 MB RAM, 500MHz or faster, DirectX: 7.0<\/p>"
},
"mac_requirements": [
],
"linux_requirements": [
],
"developers": [
"PopCap Games, Inc."
],
"publishers": [
"PopCap Games, Inc."
],
"demos": [
{
"appid": 3402,
"description": ""
}
],
"price_overview": {
"currency": "USD",
"initial": 499,
"final": 499,
"discount_percent": 0
},
"packages": [
135
],
"package_groups": [
{
"name": "default",
"title": "Buy Hammer Heads Deluxe",
"description": "",
"selection_text": "Select a purchase option",
"save_text": "",
"display_type": 0,
"is_recurring_subscription": "false",
"subs": [
{
"packageid": 135,
"percent_savings_text": "",
"percent_savings": 0,
"option_text": "Hammer Heads Deluxe - $4.99",
"option_description": "",
"can_get_free_license": "0",
"is_free_license": false,
"price_in_cents_with_discount": 499
}
]
}
],
"platforms": {
"windows": true,
"mac": false,
"linux": false
},
"categories": [
{
"id": 2,
"description": "Single-player"
}
],
"genres": [
{
"id": "4",
"description": "Casual"
}
],
"screenshots": [
{
"id": 0,
"path_thumbnail": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/3400\/0000000564.600x338.jpg?t=1447350883",
"path_full": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/3400\/0000000564.1920x1080.jpg?t=1447350883"
},
{
"id": 1,
"path_thumbnail": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/3400\/0000000565.600x338.jpg?t=1447350883",
"path_full": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/3400\/0000000565.1920x1080.jpg?t=1447350883"
},
{
"id": 2,
"path_thumbnail": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/3400\/0000000566.600x338.jpg?t=1447350883",
"path_full": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/3400\/0000000566.1920x1080.jpg?t=1447350883"
},
{
"id": 3,
"path_thumbnail": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/3400\/0000000567.600x338.jpg?t=1447350883",
"path_full": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/3400\/0000000567.1920x1080.jpg?t=1447350883"
},
{
"id": 4,
"path_thumbnail": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/3400\/0000000568.600x338.jpg?t=1447350883",
"path_full": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/3400\/0000000568.1920x1080.jpg?t=1447350883"
}
],
"release_date": {
"coming_soon": false,
"date": "Aug 30, 2006"
},
"support_info": {
"url": "",
"email": ""
},
"background": "http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/3400\/page_bg_generated_v6b.jpg?t=1447350883"
}
}
}
That is the json block returned for accessing appid 3400. Note how it's appid is located inside of file itself.
In order to generate classes for this, I made a formatted version of that based off the unofficial storefront api documentation. Then I used that to generate the container classes shown below.
public class Appid
{
public bool success { get; set; }
public Data data { get; set; }
}
public class Data
{
public string type { get; set; }
public string name { get; set; }
public int steam_appid { get; set; }
public int required_age { get; set; }
public int[] dlc { get; set; }
public string detailed_description { get; set; }
public string about_the_game { get; set; }
public Fullgame fullgame { get; set; }
public string supported_languages { get; set; }
public string header_image { get; set; }
public string website { get; set; }
public Pc_Requirements pc_requirements { get; set; }
public Mac_Requirements mac_requirements { get; set; }
public Linux_Requirements linux_requirements { get; set; }
public string[] developers { get; set; }
public Demos demos { get; set; }
public Price_Overview price_overview { get; set; }
public int[] packages { get; set; }
public Package_Groups[] package_groups { get; set; }
public Platforms platforms { get; set; }
public Metacritic metacritic { get; set; }
public Category[] categories { get; set; }
public Screenshot[] screenshots { get; set; }
public Movie[] movies { get; set; }
public Recommendations recommendations { get; set; }
public Achievements achievements { get; set; }
public Release_Date release_date { get; set; }
}
public class Fullgame
{
public int appid { get; set; }
public string name { get; set; }
}
public class Pc_Requirements
{
public string minimum { get; set; }
public string recommended { get; set; }
}
public class Mac_Requirements
{
public string minimum { get; set; }
public string recommended { get; set; }
}
public class Linux_Requirements
{
public string minimum { get; set; }
public string recommended { get; set; }
}
public class Demos
{
public int appid { get; set; }
public string description { get; set; }
}
public class Price_Overview
{
public string currency { get; set; }
public int initial { get; set; }
public int final { get; set; }
public int discount_precent { get; set; }
}
public class Platforms
{
public bool windows { get; set; }
public bool mac { get; set; }
public bool linux { get; set; }
}
public class Metacritic
{
public int score { get; set; }
public string url { get; set; }
}
public class Recommendations
{
public int total { get; set; }
}
public class Achievements
{
public int total { get; set; }
public Highlighted[] highlighted { get; set; }
}
public class Highlighted
{
public string name { get; set; }
public string path { get; set; }
}
public class Release_Date
{
public bool coming_soon { get; set; }
public string date { get; set; }
}
public class Package_Groups
{
public string name { get; set; }
public string title { get; set; }
public string description { get; set; }
public string selection_text { get; set; }
public string save_text { get; set; }
public int display_type { get; set; }
public string is_recurring_subscription { get; set; }
public Sub[] subs { get; set; }
}
public class Sub
{
public int packageid { get; set; }
public string percent_savings_text { get; set; }
public int percent_savings { get; set; }
public string option_text { get; set; }
public string option_description { get; set; }
}
public class Category
{
public int id { get; set; }
public string description { get; set; }
}
public class Screenshot
{
public int id { get; set; }
public string path_thumbnail { get; set; }
public string path_full { get; set; }
}
public class Movie
{
public int id { get; set; }
public string name { get; set; }
public string thumbnail { get; set; }
public Webm webm { get; set; }
}
public class Webm
{
public string _480 { get; set; }
public string max { get; set; }
}
Now onto the code, the function takes in a long and should return a Data object. However, instead of deserializing, it returns a null. I have checked to make sure the json is actually getting to the code. It is coming in fine.
//Steam rest stuff always returns with one object.
//This it to keep me writing 10 classes that do essentially the same thing
//And before you ask, yes, I have tried doing this without this class.
//Still didn't work.
public class RootObject<T>
{
public T response { get; set; }
}
public static Data GetGameData(long appid)
{
//Only thing different about this function except for the fact that it's also static
RestClient storeClient = new RestClient("http://store.steampowered.com/api/");
RestRequest restReq = new RestRequest("appdetails/", Method.GET);
restReq.AddParameter("appids", appid);
restReq.RequestFormat = DataFormat.Json;
restReq.OnBeforeDeserialization = resp =>
{
//This was done as an attempt to fix it.
//It makes the appid's in the content into {"appId":{
//EX: {"400":{ -> {"appId":{
resp.Content = Regex.Replace(resp.Content, "{\"\\d+\":{", "{\"appId\":{");
};
IRestResponse<RootObject<Appid>> response = storeClient.Execute<RootObject<Appid>>(restReq);
Appid trueRes = response.Data.response;
return trueRes.data;
}
Quick note, the function was altered but only to work in a static context.
The edit was noted in code.
Things I've tried
Explicitly specifying that the file is a json file.
Changing the appid class names to a common class name.
Using Json.Net as the deserializer.
Removing the "success": true item.
Using [DeserializeAs(Name = "appId")] in the appid class.
Using a non generic version of RootObject
Tried using Dictionary<string, Appid> instead of RootObject<Appid>
Edit:
For some extra information I did some testing on the methods.
I remade the object carrying classes using appid 4000 and put that into json to sharp converter. Then I wrote a small bit of code that tested if the data was null.
static void TestIfFetched(long appid)
{
Console.Write($"{appid}\t:");
Data data = GetGameData(appid);
if (data == null)
{
Console.WriteLine("Failed to get data.");
}
else
{
Console.WriteLine("Data fetched successfully.");
}
}
The result was this when testing 4000 and 400.
4000 :Failed to get data.
400 :Failed to get data.
So it seems even using data specifically designed for that game, it still fails to parse.
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
RestClient storeClient = new RestClient("https://store.steampowered.com/api/");
RestRequest restReq = new RestRequest("appdetails/", Method.GET);
restReq.AddParameter("appids", appid);
restReq.RequestFormat = DataFormat.Json;
var response = storeClient.Execute<dynamic>(restReq);
JObject jObject = JObject.Parse(response.Content);
var details = jObject[appid].Value<JObject>().ToObject<Appid>();
The above worked for me. The JObject allows you to pass the appid as a parameter and then parse your object from there.

Get information from a json string?

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 :

Categories

Resources