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; }
}
Related
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; }
New to C# and JSON but basically I have to use a C# script component in SSIS to extract data from a web service. I was able to do it initially with a different JSON format but this one includes an array.
I get the following error:
"Type 'Rootobject' is not supported for deserialization of an array."
Below is how I call the Deserializer:
//Deserialize our JSON
JavaScriptSerializer sr = new
jsonResponse = sr.Deserialize<Rootobject>(responseFromServer);
Here is my JSON structure (not quite all since fairly large):
[
{
"status":"SUCCESS",
"object":{
"responseStatusCode":0,
"productId":"35100003",
"cansimId":"251-0008",
"cubeTitleEn":"Average counts of young persons in provincial and territorial correctional services",
"cubeTitleFr":"Comptes moyens des adolescents dans les services correctionnels provinciaux et territoriaux",
"cubeStartDate":"1997-01-01",
"cubeEndDate":"2017-01-01",
"frequencyCode":12,
"nbSeriesCube":174,
"nbDatapointsCube":3468,
"releaseTime":"2019-05-09T08:30",
"archiveStatusCode":"2",
"archiveStatusEn":"CURRENT - a cube available to the public and that is current",
"archiveStatusFr":"ACTIF - un cube qui est disponible au public et qui est toujours mise a jour",
"subjectCode":[
"350102",
"4211"
],
"surveyCode":[
"3313"
],
"dimension":[ ],
"footnote":[ ],
"correction":[
]
}
}
]
Finally here is my Class structure obtained through Paste Special in Visual Studio:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string status { get; set; }
public Object _object { get; set; }
}
public class Object
{
public int responseStatusCode { get; set; }
public string productId { get; set; }
public string cansimId { get; set; }
public string cubeTitleEn { get; set; }
public string cubeTitleFr { get; set; }
public string cubeStartDate { get; set; }
public string cubeEndDate { get; set; }
public int frequencyCode { get; set; }
public int nbSeriesCube { get; set; }
public int nbDatapointsCube { get; set; }
public string releaseTime { get; set; }
public string archiveStatusCode { get; set; }
public string archiveStatusEn { get; set; }
public string archiveStatusFr { get; set; }
public string[] subjectCode { get; set; }
public string[] surveyCode { get; set; }
public Dimension[] dimension { get; set; }
public Footnote[] footnote { get; set; }
public object[] correction { get; set; }
}
public class Dimension
{
public int dimensionPositionId { get; set; }
public string dimensionNameEn { get; set; }
public string dimensionNameFr { get; set; }
public bool hasUom { get; set; }
public Member[] member { get; set; }
}
public class Member
{
public int memberId { get; set; }
public int? parentMemberId { get; set; }
public string memberNameEn { get; set; }
public string memberNameFr { get; set; }
public string classificationCode { get; set; }
public string classificationTypeCode { get; set; }
public int? geoLevel { get; set; }
public int? vintage { get; set; }
public int terminated { get; set; }
public int? memberUomCode { get; set; }
}
public class Footnote
{
public int footnoteId { get; set; }
public string footnotesEn { get; set; }
public string footnotesFr { get; set; }
public Link link { get; set; }
}
public class Link
{
public int footnoteId { get; set; }
public int dimensionPositionId { get; set; }
public int memberId { get; set; }
}
I know the problem lies within how I call the Deserialize<Rootobject> and different data types but I wasn't able to find the solution. Any suggestions are appreciated.
AV
Try deserializing directly to a list of Class1.
jsonResponse = sr.Deserialize<List<Class1>>(responseFromServer);
Also, don't use Object as your class name. That's a really bad practice.
You can control how JSON.NET serializes/deserializes a property as shown here: How can I change property names when serializing with Json.net?
e.g.
[JsonProperty(PropertyName = "object")]
public class MyObject
{
}
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;
I have been hitting a wall for days with this.
Can someone please tell me how to deserialize this? I can deserialize single json but deserializing an array has got me stumped.
[
{
"msys": {
"message_event": {
"type": "bounce",
"bounce_class": "1",
"campaign_id": "Example Campaign Name",
"customer_id": "1",
"delv_method": "esmtp",
"device_token": "45c19189783f867973f6e6a5cca60061ffe4fa77c547150563a1192fa9847f8a",
"error_code": "554",
"ip_address": "127.0.0.1",
"message_id": "0e0d94b7-9085-4e3c-ab30-e3f2cd9c273e",
"msg_from": "sender#example.com",
"msg_size": "1337",
"num_retries": "2",
"rcpt_meta": {
"customKey": "customValue"
},
"rcpt_tags": [
"male",
"US"
],
"rcpt_to": "recipient#example.com",
"rcpt_type": "cc",
"raw_reason": "MAIL REFUSED - IP (17.99.99.99) is in black list",
"reason": "MAIL REFUSED - IP (a.b.c.d) is in black list",
"routing_domain": "example.com",
"subject": "Summer deals are here!",
"template_id": "templ-1234",
"template_version": "1",
"timestamp": 1427736822,
"transmission_id": "65832150921904138"
}
}
}
]
My classes are defined as:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public Msys msys { get; set; }
}
public class Msys
{
public Message_Event message_event { get; set; }
}
public class Message_Event
{
public string type { get; set; }
public string bounce_class { get; set; }
public string campaign_id { get; set; }
public string customer_id { get; set; }
public string delv_method { get; set; }
public string device_token { get; set; }
public string error_code { get; set; }
public string ip_address { get; set; }
public string message_id { get; set; }
public string msg_from { get; set; }
public string msg_size { get; set; }
public string num_retries { get; set; }
public Rcpt_Meta rcpt_meta { get; set; }
public string[] rcpt_tags { get; set; }
public string rcpt_to { get; set; }
public string rcpt_type { get; set; }
public string raw_reason { get; set; }
public string reason { get; set; }
public string routing_domain { get; set; }
public string subject { get; set; }
public string template_id { get; set; }
public string template_version { get; set; }
public int timestamp { get; set; }
public string transmission_id { get; set; }
}
public class Rcpt_Meta
{
public string customKey { get; set; }
}
In my case this works. You need to tell Newtonsoft.Json what is your destinationt type (array = list):
var des = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Class1>>(json);
This is a simple complete example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NewtonSoftSample
{
class Program
{
static void Main(string[] args)
{
string json =
#"
[
{
""msys"": {
""message_event"": {
""type"": ""bounce"",
""bounce_class"": ""1"",
""campaign_id"": ""Example Campaign Name"",
""customer_id"": ""1"",
""delv_method"": ""esmtp"",
""device_token"": ""45c19189783f867973f6e6a5cca60061ffe4fa77c547150563a1192fa9847f8a"",
""error_code"": ""554"",
""ip_address"": ""127.0.0.1"",
""message_id"": ""0e0d94b7-9085-4e3c-ab30-e3f2cd9c273e"",
""msg_from"": ""sender#example.com"",
""msg_size"": ""1337"",
""num_retries"": ""2"",
""rcpt_meta"": {
""customKey"": ""customValue""
},
""rcpt_tags"": [
""male"",
""US""
],
""rcpt_to"": ""recipient#example.com"",
""rcpt_type"": ""cc"",
""raw_reason"": ""MAIL REFUSED - IP (17.99.99.99) is in black list"",
""reason"": ""MAIL REFUSED - IP (a.b.c.d) is in black list"",
""routing_domain"": ""example.com"",
""subject"": ""Summer deals are here!"",
""template_id"": ""templ-1234"",
""template_version"": ""1"",
""timestamp"": 1427736822,
""transmission_id"": ""65832150921904138""
}
}
}
]
";
var des = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Class1>>(json);
Console.WriteLine("Done");
Console.ReadLine();
}
}
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public Msys msys { get; set; }
}
public class Msys
{
public Message_Event message_event { get; set; }
}
public class Message_Event
{
public string type { get; set; }
public string bounce_class { get; set; }
public string campaign_id { get; set; }
public string customer_id { get; set; }
public string delv_method { get; set; }
public string device_token { get; set; }
public string error_code { get; set; }
public string ip_address { get; set; }
public string message_id { get; set; }
public string msg_from { get; set; }
public string msg_size { get; set; }
public string num_retries { get; set; }
public Rcpt_Meta rcpt_meta { get; set; }
public string[] rcpt_tags { get; set; }
public string rcpt_to { get; set; }
public string rcpt_type { get; set; }
public string raw_reason { get; set; }
public string reason { get; set; }
public string routing_domain { get; set; }
public string subject { get; set; }
public string template_id { get; set; }
public string template_version { get; set; }
public int timestamp { get; set; }
public string transmission_id { get; set; }
}
public class Rcpt_Meta
{
public string customKey { get; set; }
}
}
You're coming with the wrong approach. You want to be able not to know what fields the json contains but only that it will be a valid json object that can be parsed.
I'd first recommend you to understand what json object really is and what it can be composed from. You can read it here
Next, you can use this as a json parser.
Documentation about the use can be found here.
Try deserializing to a List<Class1>
var list = JsonConvert.DeserializeObject<List<Class1>>(json);
foreach (Message_Event msg in list.Select(c => c.msys.message_event))
{
Console.WriteLine("campaign: " + msg.campaign_id);
Console.WriteLine("from: " + msg.msg_from);
Console.WriteLine("to: " + msg.rcpt_to);
// etc.
}
Fiddle: https://dotnetfiddle.net/Ei0apw
You can use:
public class Msys
{
public List<Message_Event> message_event { get; set; }
}
And initialize your List<> with
System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Message_Event>(json);
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.