How to deserialize specific json string to ASP.NET MVC model? - c#

I have json string like this:
{
"data": [
{
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
...
"quote": {
"USD": {
"price": 9283.92,
"volume_24h": 7155680000,
"percent_change_1h": -0.152774,
"percent_change_24h": 0.518894,
"market_cap": 158055024432,
"last_updated": "2018-08-09T22:53:32.000Z"
},
"BTC": {
"price": 1,
"volume_24h": 772012,
"percent_change_1h": 0,
"percent_change_24h": 0,
"percent_change_7d": 0,
"market_cap": 17024600,
"last_updated": "2018-08-09T22:53:32.000Z"
}
}
},
// objects like previous from which i need the data
],
"status": {
"timestamp": "2018-06-02T22:51:28.209Z",
...
}
}
How do I deserialize it into models like this:
public class MyModel
{
public string Name { get; set; }
public string Symbol { get; set; }
public string Price { get; set; }
public double Percent_change_1h { get; set; }
public double Percent_change_24h { get; set; }
public long Market_cap { get; set; }
public DateTime Last_updated { get; set; }
}
The field names in the model are the same as the key names in json string.
I'm new to C# and I couldn't find any helpful information about my question, especially because of this specific json string structure.
I'll be glad if you direct me any good links about this.

The model seems to be something like this.
public class Model
{
public List<Datum> data { get; set; }
public Status status { get; set; }
}
public class Status
{
public DateTime timestamp { get; set; }
}
public class Datum
{
public int id { get; set; }
public string name { get; set; }
public string symbol { get; set; }
public Quote quote { get; set; }
}
public class Quote
{
public USD USD { get; set; }
public BTC BTC { get; set; }
}
public class BTC
{
public int price { get; set; }
public int volume_24h { get; set; }
public int percent_change_1h { get; set; }
public int percent_change_24h { get; set; }
public int percent_change_7d { get; set; }
public int market_cap { get; set; }
public DateTime last_updated { get; set; }
}
public class USD
{
public double price { get; set; }
public object volume_24h { get; set; }
public double percent_change_1h { get; set; }
public double percent_change_24h { get; set; }
public object market_cap { get; set; }
public DateTime last_updated { get; set; }
}
You can also try creating model on (http://json2csharp.com/) by copying your valid json string.
Please let me know if this helps

Bottom line: You can (manually), but that's probably not what you're looking for.
Reason: Your model doesn't match the JSON structure, hence "manual"
You can use readily available tools in either Visual Studio or VS Code to help you with creating the proper model (e.g. Paste JSON As Code)
Once you get the "proper" model/s ready, go over JSON documentation for (de)serializing.

I had to fix some syntax errors on your json, so fixed version is following:
{
"data": [
{
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"quote": {
"USD": {
"price": 9283.92,
"volume_24h": 7155680000,
"percent_change_1h": -0.152774,
"percent_change_24h": 0.518894,
"market_cap": 158055024432,
"last_updated": "2018-08-09T22:53:32.000Z"
},
"BTC": {
"price": 1,
"volume_24h": 772012,
"percent_change_1h": 0,
"percent_change_24h": 0,
"percent_change_7d": 0,
"market_cap": 17024600,
"last_updated": "2018-08-09T22:53:32.000Z"
}
}
}
],
"status": {
"timestamp": "2018-06-02T22:51:28.209Z"
}
}
Here is C# model classes matching with previous json:
public class Rootobject
{
public Datum[] data { get; set; }
public Status status { get; set; }
}
public class Status
{
public DateTime timestamp { get; set; }
}
public class Datum
{
public int id { get; set; }
public string name { get; set; }
public string symbol { get; set; }
public Quote quote { get; set; }
}
public class Quote
{
public USD USD { get; set; }
public BTC BTC { get; set; }
}
public class USD
{
public float price { get; set; }
public long volume_24h { get; set; }
public float percent_change_1h { get; set; }
public float percent_change_24h { get; set; }
public long market_cap { get; set; }
public DateTime last_updated { get; set; }
}
public class BTC
{
public int price { get; set; }
public int volume_24h { get; set; }
public int percent_change_1h { get; set; }
public int percent_change_24h { get; set; }
public int percent_change_7d { get; set; }
public int market_cap { get; set; }
public DateTime last_updated { get; set; }
}
Here is code snippet which you can use when deserializing your json. This snippet uses Json.NET-library.
var obj = JsonConvert.DeserializeObject<Rootobject>(File.ReadAllText("object.json"));

Related

Value from deserialized JSON string is 0

I'm trying to get the amount of pieces belonging to a certain Lego set using the Brickset API (https://brickset.com/article/52664/api-version-3-documentation)
When writing the Json string to the console it displays the amount of pieces correct. Howeever after deserializing and then writing only the value of pieces to the console it displays 0. All other properties are also not displayed when written to the console.
Result after writing the Json string to the console
{"status":"success","matches":1,"sets":\[
{
"setID": 31844,
"number": "10293",
"numberVariant": 1,
"name": "Santa's Visit",
"year": 2021,
"theme": "Icons",
"themeGroup": "Model making",
"subtheme": "Winter Village Collection",
"category": "Normal",
"released": true,
"pieces": 1445,
"minifigs": 4,
"image": {
"thumbnailURL": "https://images.brickset.com/sets/small/10293-1.jpg",
"imageURL": "https://images.brickset.com/sets/images/10293-1.jpg"
},
"bricksetURL": "https://brickset.com/sets/10293-1",
"collection": {},
"collections": {
"ownedBy": 9350,
"wantedBy": 2307
},
"LEGOCom": {
"US": {
"retailPrice": 99.99,
"dateFirstAvailable": "2021-09-17T00:00:00Z"
},
"UK": {
"retailPrice": 89.99,
"dateFirstAvailable": "2021-09-17T00:00:00Z"
},
"CA": {
"retailPrice": 139.99,
"dateFirstAvailable": "2021-09-17T00:00:00Z"
},
"DE": {
"retailPrice": 99.99,
"dateFirstAvailable": "2021-09-17T00:00:00Z"
}
},
"rating": 4.3,
"reviewCount": 0,
"packagingType": "Box",
"availability": "LEGO exclusive",
"instructionsCount": 15,
"additionalImageCount": 13,
"ageRange": {
"min": 18
},
"dimensions": {
"height": 28.0,
"width": 47.9,
"depth": 8.7,
"weight": 1.656
},
"barcode": {
"EAN": "5702016914313"
},
"extendedData": {
"tags": \[
"Santa Claus|n",
"18 Plus",
"Baked Goods",
"Bedroom",
"Bird",
"Brick Built Tree",
"Brick Separator",
"Christmas",
"Christmas Tree",
"D2c",
"Fireplace",
"Furniture",
"House",
"Kitchen",
"Light Brick",
"Mail",
"Microscale",
"Musical",
"Rocket",
"Seasonal",
"Winter Village"
\]
},
"lastUpdated": "2022-10-03T08:24:39.49Z"
}
\]}
Main Code
class Program
{
static async Task Main(string[] args)
{
await askSetNumber();
}
private async Task GetPosts(string url)
{
HttpClient client = new HttpClient();
string response = await client.GetStringAsync(url);
Console.WriteLine(response);
var set = JsonConvert.DeserializeObject<Rootobject>(response);
Console.WriteLine(set.pieces);
}
static async Task askSetNumber()
{
Console.WriteLine("Please enter a setnumber: ");
string setNumber = "{'setNumber':'" + Console.ReadLine().ToString() + "-1'}";
string url = "https://brickset.com/api/v3.asmx/getSets?apiKey=[APIKey here]&userHash=&params=" + setNumber;
Console.WriteLine(url);
Program program = new Program();
await program.GetPosts(url);
}
}
I made all classes by Pasting the Json as classes, This is the class of the object I need the data off
public class Rootobject
{
public int setID { get; set; }
public string number { get; set; }
public int numberVariant { get; set; }
public string name { get; set; }
public int year { get; set; }
public string theme { get; set; }
public string themeGroup { get; set; }
public string subtheme { get; set; }
public string category { get; set; }
public bool released { get; set; }
public int pieces { get; set; }
public int minifigs { get; set; }
public Image image { get; set; }
public string bricksetURL { get; set; }
public Collection collection { get; set; }
public Collections collections { get; set; }
public Legocom LEGOCom { get; set; }
public float rating { get; set; }
public int reviewCount { get; set; }
public string packagingType { get; set; }
public string availability { get; set; }
public int instructionsCount { get; set; }
public int additionalImageCount { get; set; }
public Agerange ageRange { get; set; }
public Dimensions dimensions { get; set; }
public Barcode barcode { get; set; }
public Extendeddata extendedData { get; set; }
public DateTime lastUpdated { get; set; }
}
I tried the example from How to get some values from a JSON string in C#? but set.pieces keeps returning 0.
This is my first time trying this kind of stuff, but I am stuck on this part.
Rootobject does not contain the same information as the json string you outputted to the console (it also escapes square brackets for some reason), so you either need to specify the entire object or navigate the json tree to get the value you require.
This is not a particularly good or robust solution, but you could replace the var set portion of you code with:
JsonDocument doc = JsonDocument.Parse(response);
if (!doc.RootElement.TryGetProperty("sets", out JsonElement sets)) return;
foreach(var set in sets.EnumerateArray())
{
if (!set.TryGetProperty("pieces", out JsonElement pieces)) continue;
Console.WriteLine(pieces.GetInt32());
}
(You'll also need using System.Text.Json; rather than the newtonsoft one.)
you have you json at first,since you have some strange "/" chars, after this you have to fix your classes too
json=json.Replace("\\[","[").Replace("\\]","]");
Set set = JsonConvert.DeserializeObject<Set>(json);
public class Set
{
public string status { get; set; }
public int matches { get; set; }
public List<SetItem> sets { get; set; }
}
public class SetItem
{
public int setID { get; set; }
public string number { get; set; }
public int numberVariant { get; set; }
public string name { get; set; }
public int year { get; set; }
public string theme { get; set; }
public string themeGroup { get; set; }
public string subtheme { get; set; }
public string category { get; set; }
public bool released { get; set; }
public int pieces { get; set; }
public int minifigs { get; set; }
public Image image { get; set; }
public string bricksetURL { get; set; }
public Collection collection { get; set; }
public Collections collections { get; set; }
public LEGOCom LEGOCom { get; set; }
public double rating { get; set; }
public int reviewCount { get; set; }
public string packagingType { get; set; }
public string availability { get; set; }
public int instructionsCount { get; set; }
public int additionalImageCount { get; set; }
public AgeRange ageRange { get; set; }
public Dimensions dimensions { get; set; }
public Barcode barcode { get; set; }
public ExtendedData extendedData { get; set; }
public DateTime lastUpdated { get; set; }
}
public class LEGOCom
{
public Country US { get; set; }
public Country UK { get; set; }
public Country CA { get; set; }
public Country DE { get; set; }
}
public class AgeRange
{
public int min { get; set; }
}
public class Barcode
{
public string EAN { get; set; }
}
public class Country
{
public double retailPrice { get; set; }
public DateTime dateFirstAvailable { get; set; }
}
and maybe it make some sense to define LEGOCom as a Dictionary, if you have much more countries
public Dictionary<string,Country> LEGOCom { get; set; }

Null Object-DeSerializing JSON C#

Returned object :
{
"_expands": [],
"size": 3,
"start": 3,
"limit": 3,
"isLastPage": false,
"_links": {
"base": "http://host:port/context/rest/desk",
"context": "context",
"next": "http://host:port/context/rest/desk",
"prev": "http://host:port/context/rest/desk"
},
"values": [
{
"status": "Waiting for Customer",
"statusDate": {
"iso8601": "2015-10-08T14:05:00+0700",
"polaris": "2015-10-08T14:05:00.000+0700",
"friendly": "Today 14:05 PM",
"epochMillis": 1444287900000
}
},
{
"status": "Waiting for Support",
"statusDate": {
"iso8601": "2015-10-08T14:01:00+0700",
"polaris": "2015-10-08T14:01:00.000+0700",
"friendly": "Today 14:01 PM",
"epochMillis": 1444287660000
}
},
{
"status": "Waiting for Customer",
"statusDate": {
"iso8601": "2015-10-08T14:00:00+0700",
"polaris": "2015-10-08T14:00:00.000+0700",
"friendly": "Today 14:00 PM",
"epochMillis": 1444287600000
}
}
]
}
Classes :
public class polarisState
{
public string[] expands { get; set; }
public int size { get; set; }
public int start { get; set; }
public int limit { get; set; }
public bool isLastPage { get; set; }
public _links links { get; set; }
public values[] values { get; set; }
}
public class _links
{
//public string base {get; set;}
public string context { get; set; }
public string next { get; set; }
public string prev { get; set; }
}
public class values
{
public string status { get; set; }
public statusDate statusDate { get; set; }
}
public class statusDate
{
public string iso8601 { get; set; }
public string polaris { get; set; }
public string friendly { get; set; }
public int epochMillis { get; set; }
}
code below :
if (resp2.IsSuccessStatusCode)
{
var values = JsonConvert.DeserializeObject<JiraState>(resp2.Content.ReadAsStringAsync().Result); }
You should change the class polarisState to
public class polarisState
{
public List<string> expands { get; set; }
public int size { get; set; }
public int start { get; set; }
public int limit { get; set; }
public bool isLastPage { get; set; }
public _links links { get; set; }
public List<values> values { get; set; }
}
array to List.
Then change the statusDate to:
public class statusDate
{
public string iso8601 { get; set; }
public string polaris { get; set; }
public string friendly { get; set; }
public long epochMillis { get; set; }
}
change the epochMillis from int to long value type.
It's done.
Use the async method and change the code as follow:
var content = await resp2.Content.ReadAsStringAsync();
var values = JsonConvert.DeserializeObject<polarisState>(content);

Problems Deserialising a nested object array

Here are my models:
public class Order
{
public IEnumerable<LineItem> LineItems { get; set; }
}
public class LineItem
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("product_id")]
public int ProductId { get; set; }
[JsonPropertyName("variation_id")]
public int VariationId { get; set; }
[JsonPropertyName("quantity")]
public int Quantity { get; set; }
[JsonPropertyName("tax_class")]
public string TaxClass { get; set; }
[JsonPropertyName("subtotal")]
public string Subtotal { get; set; }
[JsonPropertyName("subtotal_tax")]
public string SubtotalTax { get; set; }
[JsonPropertyName("total")]
public string Total { get; set; }
[JsonPropertyName("total_tax")]
public string TotalTax { get; set; }
[JsonPropertyName("taxes")]
public List<object> Taxes { get; set; }
[JsonPropertyName("meta_data")]
public List<MetaData> MetaData { get; set; }
[JsonPropertyName("sku")]
public string Sku { get; set; }
[JsonPropertyName("price")]
public double Price { get; set; }
[JsonPropertyName("parent_name")]
public string ParentName { get; set; }
}
As you can see the HttpRequest property contains an array of line items:
[
{
"id":7928,
"parent_id":0,
"status":"on-hold",
"currency":"GBP",
"version":"5.7.1",
"prices_include_tax":true,
"date_created":"2021-10-04T00:26:22",
"date_modified":"2021-10-04T00:26:22",
"discount_total":"0.00",
"discount_tax":"0.00",
"shipping_total":"0.00",
"shipping_tax":"0.00",
"cart_tax":"0.00",
"total":"2.50",
"total_tax":"0.00",
"customer_id":3,
"order_key":"redacted",
"billing":{
"first_name":"redacted",
"last_name":"redacted",
"company":"",
"address_1":"redacted",
"address_2":"redacted",
"city":"redacted",
"state":"redacted",
"postcode":"redacted",
"country":"GB",
"email":"redacted",
"phone":"redacted"
},
"shipping":{
"first_name":"redacted",
"last_name":"redacted",
"company":"",
"address_1":"redacted",
"address_2":"redacted Lane",
"city":"redacted",
"state":"redacted",
"postcode":"redacted",
"country":"GB",
"phone":""
},
"payment_method":"bacs",
"payment_method_title":"Direct bank transfer",
"transaction_id":"",
"customer_ip_address":"redacted",
"customer_user_agent":"redacted",
"created_via":"redacted",
"customer_note":"",
"date_completed":null,
"date_paid":null,
"cart_hash":"redacted",
"number":"redacted",
"meta_data":[
{
"id":190011,
"key":"redacted",
"value":"no"
},
{
"id":190012,
"key":"redacted",
"value":"yes"
},
{
"id":190016,
"key":"_new_order_email_sent",
"value":"true"
},
{
"id":190017,
"key":"_thankyou_action_done",
"value":"1"
}
],
"line_items":[
{
"id":5287,
"name":"John Guest 3\/8 to 1\/4 Fitting PI0112f4S",
"product_id":5699,
"variation_id":0,
"quantity":1,
"tax_class":"",
"subtotal":"2.50",
"subtotal_tax":"0.00",
"total":"2.50",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":48648,
"key":"_WCPA_order_meta_data",
"value":"",
"display_key":"_WCPA_order_meta_data",
"display_value":""
}
],
"sku":"",
"price":2.5,
"parent_name":null
}
],
"tax_lines":[
],
"shipping_lines":[
{
"id":5288,
"method_title":"Collect from store",
"method_id":"local_pickup",
"instance_id":"13",
"total":"0.00",
"total_tax":"0.00",
"taxes":[
],
"meta_data":[
{
"id":48647,
"key":"Items",
"value":"John Guest 3\/8 to 1\/4 Fitting PI0112f4S × 1",
"display_key":"Items",
"display_value":"John Guest 3\/8 to 1\/4 Fitting PI0112f4S × 1"
}
]
}
],
"fee_lines":[
],
"coupon_lines":[
],
"refunds":[
],
"date_created_gmt":"2021-10-03T23:26:22",
"date_modified_gmt":"2021-10-03T23:26:22",
"date_completed_gmt":null,
"date_paid_gmt":null,
"currency_symbol":"\u00a3",
"_links":{
"self":[
{
"href":"redacted"
}
],
"collection":[
{
"href":"redacted"
}
],
"customer":[
{
"href":"redacted"
}
]
}
},
]
I am wondering why when this is deserialized using
public class WooCommerceOrders
{
private HttpRequestService _httpRequestService;
private string _url;
public WooCommerceOrders()
{
_httpRequestService = new HttpRequestService();
_url = "https://kegthat.com/wp-json/wc/v3/orders";
}
public List<Order> GetOrdersJson()
{
var result = _httpRequestService.CallApi(_url).Content.ReadAsStringAsync();
return _httpRequestService.DeserializeApiResponseJson<List<Order>>(result.Result);
}
}
The json for line items returns
"lineItems": null,
however some fields such as shipping return
"shipping": {
"firstName": null,
"lastName": null,
"company": "",
"address1": null,
"address2": null,
"city": "redacting city",
"state": "Cheshire",
"postcode": "redacting postcode",
"country": "GB",
"phone": ""
},
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
This wont let me add too much more code than content
Why can I not return line items?
Try this using Newtonsoft.Json
using Newtonsoft.Json;
.....
public List<Order> GetOrdersJson()
{
var result = _httpRequestService.CallApi(_url).Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject< List<Order>>(result.Result);
}
test to get line_items
var result= GetOrdersJson();
var lineItems=result[0].line_items;
[
{
"id": 5287,
"name": "John Guest 3/8 to 1/4 Fitting PI0112f4S",
"product_id": 5699,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "2.50",
"subtotal_tax": "0.00",
"total": "2.50",
"total_tax": "0.00",
"taxes": [],
"meta_data": [
{
"id": 48648,
"key": "_WCPA_order_meta_data",
"value": "",
"display_key": "_WCPA_order_meta_data",
"display_value": ""
}
],
"sku": "",
"price": 2.5,
"parent_name": null
}
]
classes
public class Order
{
public int id { get; set; }
public int parent_id { get; set; }
public string status { get; set; }
public string currency { get; set; }
public string version { get; set; }
public bool prices_include_tax { get; set; }
public DateTime date_created { get; set; }
public DateTime date_modified { get; set; }
public string discount_total { get; set; }
public string discount_tax { get; set; }
public string shipping_total { get; set; }
public string shipping_tax { get; set; }
public string cart_tax { get; set; }
public string total { get; set; }
public string total_tax { get; set; }
public int customer_id { get; set; }
public string order_key { get; set; }
public Billing billing { get; set; }
public Shipping shipping { get; set; }
public string payment_method { get; set; }
public string payment_method_title { get; set; }
public string transaction_id { get; set; }
public string customer_ip_address { get; set; }
public string customer_user_agent { get; set; }
public string created_via { get; set; }
public string customer_note { get; set; }
public object date_completed { get; set; }
public object date_paid { get; set; }
public string cart_hash { get; set; }
public string number { get; set; }
public List<MetaData> meta_data { get; set; }
public List<LineItem> line_items { get; set; }
public List<object> tax_lines { get; set; }
public List<ShippingLine> shipping_lines { get; set; }
public List<object> fee_lines { get; set; }
public List<object> coupon_lines { get; set; }
public List<object> refunds { get; set; }
public DateTime date_created_gmt { get; set; }
public DateTime date_modified_gmt { get; set; }
public object date_completed_gmt { get; set; }
public object date_paid_gmt { get; set; }
public string currency_symbol { get; set; }
public Links _links { get; set; }
}
public class Billing
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_1 { get; set; }
public string address_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postcode { get; set; }
public string country { get; set; }
public string email { get; set; }
public string phone { get; set; }
}
public class Shipping
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_1 { get; set; }
public string address_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postcode { get; set; }
public string country { get; set; }
public string phone { get; set; }
}
public class MetaData
{
public int id { get; set; }
public string key { get; set; }
public string value { get; set; }
public string display_key { get; set; }
public string display_value { get; set; }
}
public class LineItem
{
public int id { get; set; }
public string name { get; set; }
public int product_id { get; set; }
public int variation_id { get; set; }
public int quantity { get; set; }
public string tax_class { get; set; }
public string subtotal { get; set; }
public string subtotal_tax { get; set; }
public string total { get; set; }
public string total_tax { get; set; }
public List<object> taxes { get; set; }
public List<MetaData> meta_data { get; set; }
public string sku { get; set; }
public double price { get; set; }
public object parent_name { get; set; }
}
public class ShippingLine
{
public int id { get; set; }
public string method_title { get; set; }
public string method_id { get; set; }
public string instance_id { get; set; }
public string total { get; set; }
public string total_tax { get; set; }
public List<object> taxes { get; set; }
public List<MetaData> meta_data { get; set; }
}
public class Self
{
public string href { get; set; }
}
public class Collection
{
public string href { get; set; }
}
public class Customer
{
public string href { get; set; }
}
public class Links
{
public List<Self> self { get; set; }
public List<Collection> collection { get; set; }
public List<Customer> customer { get; set; }
}
IEnumerable<T> is not a valid type for the serializer. It doesn't define any concrete implementation of a collection for the serializer to parse the JSON into. Use List<T> when deserializing JSON arrays.
public List<Order> GetOrdersJson()
{
var result = _httpRequestService.CallApi(_url).Content.ReadAsStringAsync();
return _httpRequestService.DeserializeApiResponseJson<Order>(result.Result);
}
Deserializing List<Order> which is not the Deserializer is expecting.
Try return _httpRequestService.DeserializeApiResponseJson<Order> instead

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.

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.

Categories

Resources