Change values in a JSON file C# - 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:

Related

Part of JSON returned by API is serialised by JSON.NET but not all

I imagine this is more of a problem with my code rather than a problem with JSON.NET, but I'm not sure where I'm going wrong.
I have the following class below which is being used to serialise the json data found at this link: https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22
To construct this class I used a JSON to C# generator found on google.
Also below are the methods I use to pull and serialise the JSON data into a WeatherData object.
private string GetJsonFromWeb(string resource, string city)
{
var request = new RestRequest(resource, Method.GET);
request.AddParameter("q", city);
request.AddParameter("APPID", "af5e6fd579e0ddb303afc1774487c77b");
var fullUrl = client.BuildUri(request);
Console.WriteLine("Full URL: " + fullUrl.AbsoluteUri);
var response = client.Execute(request);
string json = response.Content;
return json;
}
private WeatherData SerializeJsonToWeatherData(string json)
{
WeatherData weatherData = JsonConvert.DeserializeObject<WeatherData>(json);
return weatherData;
}
These methods work successfully, as the JSON data can be used later in the application to display information within the GUI. However the MainData part of the JSON data is set to null after the JSON is pulled from the API.
class WeatherData
{
public Coord Coord { get; set; }
public List<Weather> Weather { get; set; }
public string Base { get; set; }
public MainData MainData { get; set; }
public int Visibility { get; set; }
public Wind Wind { get; set; }
public Clouds Clouds { get; set; }
public int Dt { get; set; }
public Sys Sys { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public int Cod { get; set; }
}
public class Coord
{
public double Lon { get; set; }
public double Lat { get; set; }
}
public class Weather
{
public int Id { get; set; }
public string Main { get; set; }
public string Description { get; set; }
public string Icon { get; set; }
}
public class MainData
{
public double Temp { get; set; }
public int Pressure { get; set; }
public int Humidity { get; set; }
public double Temp_min { get; set; }
public double Temp_max { get; set; }
}
public class Wind
{
public double Speed { get; set; }
public int Deg { get; set; }
}
public class Clouds
{
public int All { get; set; }
}
public class Sys
{
public int Type { get; set; }
public int Id { get; set; }
public double Message { get; set; }
public string Country { get; set; }
public int Sunrise { get; set; }
public int Sunset { get; set; }
}
Sample JSON from above API
{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 300,
"main": "Drizzle",
"description": "light intensity drizzle",
"icon": "09d"
}
],
"base": "stations",
"main": {
"temp": 280.32,
"pressure": 1012,
"humidity": 81,
"temp_min": 279.15,
"temp_max": 281.15
},
"visibility": 10000,
"wind": {
"speed": 4.1,
"deg": 80
},
"clouds": {
"all": 90
},
"dt": 1485789600,
"sys": {
"type": 1,
"id": 5091,
"message": 0.0103,
"country": "GB",
"sunrise": 1485762037,
"sunset": 1485794875
},
"id": 2643743,
"name": "London",
"cod": 200
}
The JSON property is called main not mainData. JSON.Net can't find a property called mainData ans thus does not populate the MainData property of your POCOs

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.

Deserializing a complex JSON object

I use JavaScript.Serializer.Deserializer to deserialize a complex JSON object, as below:
{
"name": "rule 1",
"enabled": true,
"conditions": [{
"type": "time",
"time": "17:23:10",
"days": "125"
}, {
"type": "sensor",
"uid": "10.2.0.1",
"setpoint1": 12,
"setpoint2": 18,
"criterion": 1
}, {
"type": "sensor",
"uid": "10.3.0.1",
"setpoint1": 12,
"setpoint2": 18,
"criterion": 2
}],
"actions": {
"period": 100,
"single": false,
"act": [{
"type": "on",
"uid": "10.1.0.1"
}, {
"type": "sms",
"message": "Hello World"
}]
}
}
And I want to convert it to some classes, like below:
public class Rule
{
public string name { get; set; }
public bool enabled { get; set; }
public List<Condition> conditions { get; set; }
public List<Action> actions { get; set; }
}
public class Condition
{
public string type { get; set; }
public string uid { get; set; }
public DateTime? time { get; set; }
public string days { get; set; }
public double setpoint1 { get; set; }
public double setpoint2 { get; set; }
public int criterion { get; set; }
}
public class Action
{
public int period { get; set; }
public bool single { get; set; }
public List<Act> act { get; set; }
}
public class Act
{
public string type { get; set; }
public string uid { get; set; }
public string message { get; set; }
}
The deserialization snippet:
json = new JavaScriptSerializer();
Rule rule = (json.Deserialize<Rule>(jsonStr));
If I simplify the Rule class and declare conditions and actions as simple strings, it works fine.
But if I use the classes like above, it throws an exception:
Cannot convert object of type 'System.String' to type 'System.Collections.Generic.List`1[IoTWebApplication.Condition]'
The structure you create does not fit to the JSON you posted.
It should look like
public class Rule
{
public string name { get; set; }
public bool enabled { get; set; }
public Condition[ ] conditions { get; set; }
public Actions actions { get; set; }
}
public class Actions
{
public int period { get; set; }
public bool single { get; set; }
public Act[ ] act { get; set; }
}
public class Act
{
public string type { get; set; }
public string uid { get; set; }
public string message { get; set; }
}
public class Condition
{
public string type { get; set; }
public string time { get; set; }
public string days { get; set; }
public string uid { get; set; }
public int setpoint1 { get; set; }
public int setpoint2 { get; set; }
public int criterion { get; set; }
}
It is (in most cases) very easy in VS to get the classes direct out of the JSON
Copy JSON to clipboard
In VS EDIT/Special Paste/Paste JSON as Classes (the code above was created by this)
The problem was that the inner (nested) json was quoted and therefore was processed as a string. So when I removed the quotes, it worked fine:
json = new JavaScriptSerializer();
Rule rule = (json.Deserialize<Rule>(jsonStr));

Deserializing an array of different object types

Using the Json.NET library, I'm having trouble deserializing some json returned as an array. The json is an array containing some paging information as an object and array of country objects. Here's a sample of the returned json:
[
{
"page": 1,
"pages": 6,
"per_page": "50",
"total": 262
},
[
{
"id": "ABW",
"iso2Code": "AW",
"name": "Aruba",
"region": {
"id": "LCN",
"value": "Latin America & Caribbean (all income levels)"
},
"adminregion": {
"id": "",
"value": ""
},
"incomeLevel": {
"id": "NOC",
"value": "High income: nonOECD"
},
"lendingType": {
"id": "LNX",
"value": "Not classified"
},
"capitalCity": "Oranjestad",
"longitude": "-70.0167",
"latitude": "12.5167"
}
]
]
I am attempting to deserialize to the following types:
class CountriesQueryResults
{
public PagingInfo PageInfo { get; set; }
public List<CountryInfo> Countries { get; set; }
}
class PagingInfo
{
public int Page { get; set; }
public int Pages { get; set; }
[JsonProperty("per_page")]
public int ResultsPerPage { get; set; }
public int Total { get; set; }
}
class CountryInfo
{
public string Id { get; set; }
public string Iso2Code { get; set; }
public string Name { get; set; }
public string Longitude { get; set; }
public string Latitude { get; set; }
public string CapitalCity { get; set; }
public CompactIdentifier Region { get; set; }
public CompactIdentifier AdminRegion { get; set; }
public CompactIdentifier IncomeLevel { get; set; }
public CompactIdentifier LendingType { get; set; }
}
class CompactIdentifier
{
public string Id { get; set; }
public string Value { get; set; }
}
I am calling DeserializeObject as so:
var data = JsonConvert.DeserializeObject<List<CountriesQueryResults>>(response);
I am getting the following error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'CountriesQueryResults' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
I have been trying to get the answer from the documentation but I can't seem to figure it out. Any help would be appreciated.
Since your json is like this [ {....} , [{....}] ], You can only deserialize it to an object array(Where first item is an object and second, another array).
This simplest way I think to convert it to a c# object is:
var jArr = JArray.Parse(jsonstr);
var pageInfo = jArr[0].ToObject<PagingInfo>();
var countryInfos = jArr[1].ToObject<List<CountryInfo>>();
Class definitions would be:
public class PagingInfo
{
public int page { get; set; }
public int pages { get; set; }
[JsonProperty("per_page")]
public int ResultsPerPage { get; set; }
public int total { get; set; }
}
public class Region
{
public string id { get; set; }
public string value { get; set; }
}
public class AdminRegion
{
public string id { get; set; }
public string value { get; set; }
}
public class IncomeLevel
{
public string id { get; set; }
public string value { get; set; }
}
public class LendingType
{
public string id { get; set; }
public string value { get; set; }
}
public class CountryInfo
{
public string id { get; set; }
public string iso2Code { get; set; }
public string name { get; set; }
public Region region { get; set; }
public AdminRegion adminregion { get; set; }
public IncomeLevel incomeLevel { get; set; }
public LendingType lendingType { get; set; }
public string capitalCity { get; set; }
public string longitude { get; set; }
public string latitude { get; set; }
}
PS: You can change the property names' first char to Uppercase if you want. I used http://json2csharp.com/ to automatically generate those classes.

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