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=¶ms=" + 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; }
Related
I am trying to access a json element with the name "long", but VS gives an error, it detects it as a 16 bit signed integer.
The other elements in Json I can access , except element "long" and "short".
Is there a way around this?
var resultOpenPositions = JsonConvert.DeserializeObject<Root>(JsonopenPositions);
string ShrtLong = resultOpenPositions.positions[0].long.units; // long here gives error , vs detects it as a 16 bit signed integer
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Long
{
public string averagePrice { get; set; }
public string pl { get; set; }
public string resettablePL { get; set; }
public List<string> tradeIDs { get; set; }
public string units { get; set; }
public string unrealizedPL { get; set; }
}
public class Short
{
public string pl { get; set; }
public string resettablePL { get; set; }
public string units { get; set; }
public string unrealizedPL { get; set; }
public string averagePrice { get; set; }
public List<string> tradeIDs { get; set; }
}
public class Position
{
public string instrument { get; set; }
public Long #long { get; set; }
public string pl { get; set; }
public string resettablePL { get; set; }
public Short #short { get; set; }
public string unrealizedPL { get; set; }
}
public class Root
{
public string lastTransactionID { get; set; }
public List<Position> positions { get; set; }
}
here is the json part:
{
"positions": [
{
"instrument": "EUR_USD",
"long": {
"units": "1",
"averagePrice": "1.13093",
"pl": "-1077.2255",
"resettablePL": "-1077.2255",
"financing": "-48.6223",
"dividendAdjustment": "0.0000",
"guaranteedExecutionFees": "0.0000",
"tradeIDs": [
"17800"
],
"unrealizedPL": "-0.0001"
},
"short": {
"units": "0",
"pl": "-543.3196",
"resettablePL": "-543.3196",
"financing": "-3.1941",
"dividendAdjustment": "0.0000",
"guaranteedExecutionFees": "0.0000",
"unrealizedPL": "0.0000"
},
"pl": "-1620.5451",
"resettablePL": "-1620.5451",
"financing": "-51.8164",
"commission": "0.0000",
"dividendAdjustment": "0.0000",
"guaranteedExecutionFees": "0.0000",
"unrealizedPL": "-0.0001",
"marginUsed": "0.0333"
}
],
"lastTransactionID": "17800"
}
Prefix the call to the property name with an #:
Keywords are predefined, reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include # as a prefix. For example, #if is a valid identifier, but if is not because if is a keyword.
string ShrtLong = resultOpenPositions.positions[0].#long.units;
Alternativelly, configure the serializer to handle camel cased json elements while having Pascal cased properties on your model.
IMHO, the best way is to use [JsonProperty] attribute. And you don't need 2 classes Long and Short, it would be enough just one.
Code
var resultOpenPositions = JsonConvert.DeserializeObject<Root(JsonopenPositions);
string ShrtLong = resultOpenPositions.positions[0].longPosition.units;
classes
public class Root
{
public string lastTransactionID { get; set; }
public List<Position> positions { get; set; }
}
public class Position
{
public string pl { get; set; }
public string instrument { get; set; }
[JsonProperty("long")]
public PositionPL longPosition { get; set; }
[JsonProperty("short")]
public PositionPL shortPosition { get; set; }
public string resettablePL { get; set; }
public string unrealizedPL { get; set; }
}
public class PositionPL
{
public string pl { get; set; }
public string averagePrice { get; set; }
public string resettablePL { get; set; }
public List<string> tradeIDs { get; set; }
public string units { get; set; }
public string unrealizedPL { get; set; }
}
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
I'm having a problem that raises an exception Newtonsoft.Json.JsonSerializationException in Newtonsoft.Json.dll when trying to deserialize an Json formatted string to an user defined object. The string that I'm reading from the file has been written before using the same object.
This is the code of deserielization (exception at the last line).
storageFile = await storageFolder.GetFileAsync(filePath);
string JsonDB = await FileIO.ReadTextAsync(storageFile);
MyDB myDB = Newtonsoft.Json.JsonConvert.DeserializeObject<MyDB>(JsonDB);
Here is the object class (Tag and Astro are enums):
public class MyDB
{
public string Version;
public DateTime Date;
public List<PhotoSpot_v0_1> Lista_v0_1;
}
public enum version
{
v0_1
}
public class PhotoSpot_v0_1
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Rating { get; set; }
public bool Reminder { get; set; }
public bool Toast { get; set; }
private double Latitude { get; set; }
private double Longitude { get; set; }
private double Altitude { get; set; }
public Geopoint Geopoint { get; set; }
public Geopoint Landmark { get; set; }
public TimeZoneInfo TimeZone { get; set; }
public string MainTag { get; set; }
public version Version { get; set; }
public Landmark_v0_1 Landmarks { get; set; }
public List<Image_v0_1> Images { get; set; }
public List<URL_v0_1> URLs { get; set; }
public List<globalVars.Tag> Tags { get; set; }
public List<Date_v0_1> Dates { get; set; }
public bool Downloaded { get; set; }
public bool Exportable { get; set; }
}
public class Landmark_v0_1
{
public bool freeLandmark { get; set; }
public string Title { get; set; }
private double Latitude { get; set; }
private double Longitude { get; set; }
private double Altitude { get; set; }
public globalVars.Astro Astro { get; set; }
}
public class Image_v0_1
{
public string imageURI { get; set; }
public bool isDownloaded { get; set; }
}
public class URL_v0_1
{
public string sURL { get; set; }
}
public class Tag_v0_1
{
//public string TagName { get; set; }
public globalVars.TagImageURL TagName { get; set; }
}
public class Date_v0_1
{
private double DateStart;
private double DateEnd;
public DateTime DateTimeStart()
{
return CoreTime.JDToDateTime(DateStart);
}
public DateTime DateTimeEnd()
{
return CoreTime.JDToDateTime(DateEnd);
}
public void SetDateTimeStart(DateTime dt)
{
DateStart = CoreTime.DateTimeToJD(dt);
}
public void SetDateTimeEnd(DateTime dt)
{
DateEnd = CoreTime.DateTimeToJD(dt);
}
}
I've checked that the Json string, before writing, after writing and when read are the same. Here it is if it's helpful. If something more is needed I'll post it.
{
"Version": "v0_1",
"Date": "2020-01-08T10:49:04.6992512+01:00",
"Lista_v0_1": [
{
"ID": 2,
"Title": "Abadi gaztelua",
"Description": "",
"Rating": 0,
"Reminder": false,
"Toast": false,
"Geopoint": {
"Position": {
"Latitude": 43.380954170570355,
"Longitude": -1.7520569699123154,
"Altitude": 87.749645113013685
},
"AltitudeReferenceSystem": 2,
"GeoshapeType": 0,
"SpatialReferenceId": 4326
},
"Landmark": null,
"TimeZone": {
"Id": "Romance Standard Time",
"DisplayName": "(UTC+01:00) Brussels, Copenhagen, Madrid, Paris",
"StandardName": "Romance Standard Time",
"DaylightName": "Romance Daylight Time",
"BaseUtcOffset": "01:00:00",
"SupportsDaylightSavingTime": true
},
"MainTag": "Monument",
"Version": 0,
"Landmarks": {
"freeLandmark": false,
"Title": null,
"Astro": 0
},
"Images": [],
"URLs": [],
"Tags": [],
"Dates": [],
"Downloaded": false,
"Exportable": true
}
]
}
I think your class is not proper. I tried your code and it's working.
string filepath = "../../../json.txt";
var test = File.ReadAllText(filepath);
Example myDB = JsonConvert.DeserializeObject<Example>(test);
pl check your following class as per your json
public class Position
{
public double Latitude { get; set; }
public double Longitude { get; set; }
public double Altitude { get; set; }
}
public class Geopoint
{
public Position Position { get; set; }
public int AltitudeReferenceSystem { get; set; }
public int GeoshapeType { get; set; }
public int SpatialReferenceId { get; set; }
}
public class TimeZone
{
public string Id { get; set; }
public string DisplayName { get; set; }
public string StandardName { get; set; }
public string DaylightName { get; set; }
public string BaseUtcOffset { get; set; }
public bool SupportsDaylightSavingTime { get; set; }
}
public class Landmarks
{
public bool freeLandmark { get; set; }
public object Title { get; set; }
public int Astro { get; set; }
}
public class ListaV01
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Rating { get; set; }
public bool Reminder { get; set; }
public bool Toast { get; set; }
public Geopoint Geopoint { get; set; }
public object Landmark { get; set; }
public TimeZone TimeZone { get; set; }
public string MainTag { get; set; }
public int Version { get; set; }
public Landmarks Landmarks { get; set; }
public IList<object> Images { get; set; }
public IList<object> URLs { get; set; }
public IList<object> Tags { get; set; }
public IList<object> Dates { get; set; }
public bool Downloaded { get; set; }
public bool Exportable { get; set; }
}
public class MyDB
{
public string Version { get; set; }
public DateTime Date { get; set; }
public IList<ListaV01> Lista_v0_1 { get; set; }
}
I get a json string from an external web service. I would like to save the events from the events array in my database. How can I get List<FacebookEvents>?
My current attempt doesn't work:
List< FacebookEvents > my_obj = JsonConvert.DeserializeObject < FacebookEvents > (jsonString);
Source json:
{
"events": [{
"id": "163958810691757",
"name": "3Bridge Records presents inTRANSIT w/ David Kiss, Deep Woods, Eric Shans",
"coverPicture": "https://scontent.xx.fbcdn.net/t31.0-8/s720x720/13679859_10153862492796325_8533542782240254857_o.jpg",
"profilePicture": "https://scontent.xx.fbcdn.net/v/t1.0-0/c133.0.200.200/p200x200/13872980_10153862492796325_8533542782240254857_n.jpg?oh=a46813bbf28ad7b8bffb88acd82c7c71&oe=581EF037",
"description": "Saturday, August 20th.\n\nJoin the 3Bridge Records team for another night of sound and shenanigans - as we send Deep Woods & David Kiss out to Burning Man & belatedly celebrate Slav Ka's debut release on the label - \"Endless\" - out May 14th, featuring a remix by Mr. Shans.\n\nDavid Kiss (House of Yes)\nhttps://soundcloud.com/davidkiss\n\nDeep Woods (3Bridge Records)\nhttps://soundcloud.com/deep-woods\n\nEric Shans (3Bridge Records)\nhttps://soundcloud.com/eric-shans\n\nSlav Ka (3Bridge Records)\nhttps://soundcloud.com/slinkyslava\n\nFree before 12, $10 after (+ 1 comp well drink). $5 presale available on RA.\n\nhttps://www.residentadvisor.net/event.aspx?863815\n\nStay dope, Brooklyn.",
"distance": "203",
"startTime": "2016-08-20T22:00:00-0400",
"timeFromNow": 481946,
"stats": {
"attending": 44,
"declined": 3,
"maybe": 88,
"noreply": 1250
},
"venue": {
"id": "585713341444399",
"name": "TBA Brooklyn",
"coverPicture": "https://scontent.xx.fbcdn.net/v/t1.0-9/s720x720/13932666_1397749103574148_4391608711361541993_n.png?oh=2d82be3a458d1ce9ac8fab47cdbc6e26&oe=585E6545",
"profilePicture": "https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/12049351_1300865083262551_8221231831784471629_n.jpg?oh=a30798841ad60dfe5cfabaa4e803c3ad&oe=5854DFB9",
"location": {
"city": "Brooklyn",
"country": "United States",
"latitude": 40.711217064583,
"longitude": -73.966384349735,
"state": "NY",
"street": "395 Wythe Ave",
"zip": "11249"
}
}
},
...
],
"metadata": {
"venues": 1,
"venuesWithEvents": 1,
"events": 4
}}
class FacebookEvents
{
//[JsonProperty(PropertyName = "id")]
public string id { get; set; }
public string name { get; set; }
public string coverPicture { get; set; }
public string profilePicture { get; set; }
public string description { get; set; }
public string distance { get; set; }
public string startTime { get; set; }
public string timeFromNow { get; set; }
public Stats stats { get; set; }
}
class Stats {
public string attending { get; set; }
public string declined { get; set; }
public string maybe { get; set; }
public string noreply { get; set; }
}
class Venue
{
public string id { get; set; }
public string name { get; set; }
public string coverPicture { get; set; }
public string profilePicture { get; set; }
public Location location { get; set; }
}
class Location
{
public string city { get; set; }
public string country { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string state { get; set; }
public string street { get; set; }
public string zip { get; set; }
}
You are missing to define your RootObject which Contains List<Event> and Metadata. Full Example
public class RootObject
{
public List<Event> events { get; set; }
public Metadata metadata { get; set; }
}
public class Stats
{
public int attending { get; set; }
public int declined { get; set; }
public int maybe { get; set; }
public int noreply { get; set; }
}
public class Location
{
public string city { get; set; }
public string country { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
public string state { get; set; }
public string street { get; set; }
public string zip { get; set; }
}
public class Venue
{
public string id { get; set; }
public string name { get; set; }
public string coverPicture { get; set; }
public string profilePicture { get; set; }
public Location location { get; set; }
}
public class Event
{
public string id { get; set; }
public string name { get; set; }
public string coverPicture { get; set; }
public string profilePicture { get; set; }
public string description { get; set; }
public string distance { get; set; }
public string startTime { get; set; }
public int timeFromNow { get; set; }
public Stats stats { get; set; }
public Venue venue { get; set; }
}
public class Metadata
{
public int venues { get; set; }
public int venuesWithEvents { get; set; }
public int events { get; set; }
}
This will work:
var result = JsonConvert.DeserializeObject<RootObject>(jsonString);
EDIT:
First this is JSON, here how you can take Venue information.
foreach(var item in result.events)
{
Console.WriteLine(item.venue.name);
}
you need a root object that has an events property to store the collection
public class RootObject {
public IList<FacebookEvents> events {get;set;}
}
and then you will be able to access events
var root = JsonConvert.DeserializeObject<RootObject>(jsonString);
var events = root.events;
Lets say i have a string that looks like this
{
"_links": {
"next": "https://api.twitch.tv/kraken/users/test_user1/follows/channels?direction=DESC&limit=25&offset=25",
"self": "https://api.twitch.tv/kraken/users/test_user1/follows/channels?direction=DESC&limit=25&offset=0"
},
"follows": [
{
"created_at": "2013-06-02T09:38:45Z",
"_links": {
"self": "https://api.twitch.tv/kraken/users/test_user1/follows/channels/test_channel"
},
"channel": {
"banner": null,
"_id": 1,
"url": "http://www.twitch.tv/test_channel",
"mature": null,
"teams": [
],
"status": null,
"logo": null,
"name": "test_channel",
"video_banner": null,
"display_name": "test_channel",
"created_at": "2007-05-22T10:37:47Z",
"delay": 0,
"game": null,
"_links": {
"stream_key": "https://api.twitch.tv/kraken/channels/test_channel/stream_key",
"self": "https://api.twitch.tv/kraken/channels/test_channel",
"videos": "https://api.twitch.tv/kraken/channels/test_channel/videos",
"commercial": "https://api.twitch.tv/kraken/channels/test_channel/commercial",
"chat": "https://api.twitch.tv/kraken/chat/test_channel",
"features": "https://api.twitch.tv/kraken/channels/test_channel/features"
},
"updated_at": "2008-02-12T06:04:29Z",
"background": null
}
},
...
]
}
The part in channel is gonna appear x amount of times with the "name" part having a different value. How would I, using regex or not get the value in "name" that in the code above has a value of "test_channel". All times that it appears and then print it to a textbox
The only part I think I've managed is the regex part
string regex = #"(""name"":)\s+(\w+)(,""video_banner"")";
Using Json.Net and this site
var obj = JsonConvert.DeserializeObject<Krysvac.RootObject>(yourJsonString);
foreach(var item in obj.follows)
{
Console.WriteLine(item.channel.name);
}
public class Krysvac
{
public class Links
{
public string next { get; set; }
public string self { get; set; }
}
public class Links2
{
public string self { get; set; }
}
public class Links3
{
public string stream_key { get; set; }
public string self { get; set; }
public string videos { get; set; }
public string commercial { get; set; }
public string chat { get; set; }
public string features { get; set; }
}
public class Channel
{
public object banner { get; set; }
public int _id { get; set; }
public string url { get; set; }
public object mature { get; set; }
public List<object> teams { get; set; }
public object status { get; set; }
public object logo { get; set; }
public string name { get; set; }
public object video_banner { get; set; }
public string display_name { get; set; }
public string created_at { get; set; }
public int delay { get; set; }
public object game { get; set; }
public Links3 _links { get; set; }
public string updated_at { get; set; }
public object background { get; set; }
}
public class Follow
{
public string created_at { get; set; }
public Links2 _links { get; set; }
public Channel channel { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public List<Follow> follows { get; set; }
}
}
If you don't want to declare these classes, you can use dynamic keyword too
dynamic obj = JsonConvert.DeserializeObject(yourJsonString);
foreach(var item in obj.follows)
{
Console.WriteLine(item.channel.name);
}
If you build classes for your input string like the following using json2csharp.com, you'll get the following classes:
public class Links
{
public string next { get; set; }
public string self { get; set; }
}
public class Links2
{
public string self { get; set; }
}
public class Links3
{
public string stream_key { get; set; }
public string self { get; set; }
public string videos { get; set; }
public string commercial { get; set; }
public string chat { get; set; }
public string features { get; set; }
}
public class Channel
{
public object banner { get; set; }
public int _id { get; set; }
public string url { get; set; }
public object mature { get; set; }
public List<object> teams { get; set; }
public object status { get; set; }
public object logo { get; set; }
public string name { get; set; }
public object video_banner { get; set; }
public string display_name { get; set; }
public string created_at { get; set; }
public int delay { get; set; }
public object game { get; set; }
public Links3 _links { get; set; }
public string updated_at { get; set; }
public object background { get; set; }
}
public class Follow
{
public string created_at { get; set; }
public Links2 _links { get; set; }
public Channel channel { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public List<Follow> follows { get; set; }
}
Now you just have to deserialize the input json string to RootObject class and fetch all the names in the input string using another utility called Json.net
string json = "JSON STRING";
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
List<string> names = root.follows.Select(follow => follow.channel.name).ToList();
foreach ( string name in names )
{
txtBox += name + "; ";
}
Ok, so i got it working now, however, if i use my username to get back json, i get a huge piece of code that you can view here: https://api.twitch.tv/kraken/users/krysvac/follows/channels
I folllow 31 people but when i use my program on it with the code
using (var w = new WebClient())
{
string json_data = w.DownloadString("https://api.twitch.tv/kraken/users/" + input + "/follows/channels");
dynamic obj = JsonConvert.DeserializeObject(json_data);
foreach (var item in obj.follows)
{
textBox1.AppendText(item.channel.name.ToString() + Environment.NewLine);
}
}
i get 25 out of my 31 people back in the textbox and i dont know why, i tried it on a person that should return more than 100 and got 6 people back.