JSon String is given below:
{
"properties": {
"jci": [
{
"firstName": "Henk",
"lastName": "de Vries",
"Photo": "http://s3.amazonaws.com/mendeley-photos/6a/bd/6abdab776feb7a1fd4e5b4979ea9c5bfc754fd29.png",
"Title": "Dr.",
"Position": "Head of research group",
"Institution": "Vrije Universiteit Amsterdam",
"Fields_of_interest": ["medicine", "computer science"],
"emailAddress": "henk.de.vries#science.com",
"editorship": [
{
"title": "Dr.",
"editorial_role": "Editor in chief",
"date_start": 1460116283,
"date_end": 1460116283,
"publisher": {
"name": "Elsevier",
"role": "Project manager",
"emailAddress": "journal#elsevier.com"
}
}
]
}
],
"sid": [
{
"firstName": "Henk",
"lastName": "de Vries",
"Title": "Dr.",
"primary organisation": "Vrije Universiteit Amsterdam",
"emailAddress": "henk.de.vries#science.com",
"editorship": [
{
"title": "Dr.",
"editorial_role": "Editor in chief",
"publication_year": 2012
}
]
}
]
}
}
I have written code to deserialization
JavaScriptSerializer ser = new JavaScriptSerializer();
JsonTest foo = new JsonTest();
foo = (JsonTest)ser.Deserialize<JsonTest>(JSONString);
public class JsonTest
{
public properties properties { get; set; }
}
public class properties
{
public List<jci> jci { get; set; }
public List<sid>sid { get; set; }
}
public class jci
{
public string firstName { get; set; }
public string lastName { get; set; }
public string Photo { get; set; }
public string Position { get; set; }
public string Institution { get; set; }
public string emailAddress { get; set; }
public string Title { get; set; }
public List<string> Fields_of_interest { get; set; }
public List<editorship> editorship { get; set; }
}
public class editorship
{
public string title { get; set; }
public string editorial_role { get; set; }
public string date_start { get; set; }
public string date_end { get; set; }
public Dictionary<string, string> publisher { get; set; }
}
in this code there are 2 arrays of object called "editorship".. I have created "editorship" class for "jci".. how to access the values of editorship array of sid...?
Using json2csharp i generated these classes based on your JSON
public class Publisher
{
public string name { get; set; }
public string role { get; set; }
public string emailAddress { get; set; }
}
public class Editorship
{
public string title { get; set; }
public string editorial_role { get; set; }
public int date_start { get; set; }
public int date_end { get; set; }
public Publisher publisher { get; set; }
}
public class Jci
{
public string firstName { get; set; }
public string lastName { get; set; }
public string Photo { get; set; }
public string Title { get; set; }
public string Position { get; set; }
public string Institution { get; set; }
public List<string> Fields_of_interest { get; set; }
public string emailAddress { get; set; }
public List<Editorship> editorship { get; set; }
}
public class Editorship2
{
public string title { get; set; }
public string editorial_role { get; set; }
public int publication_year { get; set; }
}
public class Sid
{
public string firstName { get; set; }
public string lastName { get; set; }
public string Title { get; set; }
public string primary_organisation { get; set; }
public string emailAddress { get; set; }
public List<Editorship2> editorship { get; set; }
}
public class Properties
{
public List<Jci> jci { get; set; }
public List<Sid> sid { get; set; }
}
public class RootObject
{
public Properties properties { get; set; }
}
You can then access your editorial values like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
var collection = serializer.Deserialize<RootObject>(jsonString);
foreach (var j in collection.properties.sid)
{
Console.Write(j.editorship);
}
On a side note, you should consider using names that are more readable then jci and sid
Related
I'm trying to create a basic Xamarin Forms app that can list available gateways on my PFsense firewall, Show the available gateway and change this to another gateway to route through if required. The problem I have is I cannot deserialize the JSON in C# because each object has a different object name:
{
"status": "ok",
"code": 200,
"return": 0,
"message": "Success",
"data": {
"GW_WAN_1": {
"interface": "hn0",
"gateway": "192.168.0.1",
"name": "GW_WAN_1",
"weight": "1",
"ipprotocol": "inet",
"interval": "500",
"time_period": "60000",
"alert_interval": "1000",
"descr": "Interface wan Gateway",
"data_payload": "1",
"latencylow": "200",
"latencyhigh": "500",
"losslow": "10",
"losshigh": "20",
"loss_interval": "2000",
"monitor": "192.168.0.1",
"friendlyiface": "wan",
"friendlyifdescr": "RED",
"isdefaultgw": true,
"attribute": 0,
"tiername": "Default (IPv4)"
},
"INT1_DHCP6": {
"dynamic": true,
"ipprotocol": "inet6",
"gateway": "fe80::1af1:45ff:fe90:4b13",
"interface": "hn0",
"friendlyiface": "wan",
"friendlyifdescr": "RED",
"name": "INT1_DHCP6",
"attribute": "system",
"isdefaultgw": true,
"monitor": "fe80::1af1:45ff:fe90:4b13",
"descr": "Interface RED_DHCP6 Gateway",
"tiername": ""
},
"VPN_EUR_1": {
"interface": "ovpns1",
"gateway": "192.168.1.2",
"name": "VPN_EUR_1",
"weight": "1",
"ipprotocol": "inet",
"interval": "500",
"time_period": "60000",
"alert_interval": "1000",
"descr": "Interface VPN_EUR_1 Gateway",
"data_payload": "1",
"latencylow": "200",
"latencyhigh": "500",
"losslow": "10",
"losshigh": "20",
"loss_interval": "2000",
"dynamic": true,
"monitor": "192.168.1.2",
"friendlyiface": "opt4",
"friendlyifdescr": "VPN_EUR_1",
"attribute": 1,
"tiername": ""
},
"Null4": {
"name": "Null4",
"interface": "lo0",
"ipprotocol": "inet",
"gateway": "127.0.0.1",
"attribute": "system",
"tiername": ""
},
"Null6": {
"name": "Null6",
"interface": "lo0",
"ipprotocol": "inet6",
"gateway": "::1",
"attribute": "system",
"tiername": ""
},
"VPN_EUR_1V6": {
"dynamic": false,
"ipprotocol": "inet6",
"gateway": null,
"interface": "ovpns1",
"friendlyiface": "opt4",
"friendlyifdescr": "VPN_EUR_1",
"name": "VPN_EUR_1V6",
"attribute": "system",
"descr": "Interface VPN_EUR_1V6 Gateway",
"tiername": ""
}
}
}
Here's how I've gone about trying to deserialize:
string authHeader = Constants.AUTH_HEADER;
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", authHeader);
var response = await client.GetAsync(Constants.GATEWAY);
var json = await response.Content.ReadAsStringAsync();
var gateways = JsonConvert.DeserializeObject<Data>(json);
The C# Object (Generated using json to C# converter):
public class GW_WAN_1
{
public string #interface { get; set; }
public string gateway { get; set; }
public string name { get; set; }
public string weight { get; set; }
public string ipprotocol { get; set; }
public string interval { get; set; }
public string time_period { get; set; }
public string alert_interval { get; set; }
public string descr { get; set; }
public string data_payload { get; set; }
public string latencylow { get; set; }
public string latencyhigh { get; set; }
public string losslow { get; set; }
public string losshigh { get; set; }
public string loss_interval { get; set; }
public string monitor { get; set; }
public string friendlyiface { get; set; }
public string friendlyifdescr { get; set; }
public bool isdefaultgw { get; set; }
public int attribute { get; set; }
public string tiername { get; set; }
}
public class INT1_DHCP6
{
public bool dynamic { get; set; }
public string ipprotocol { get; set; }
public string gateway { get; set; }
public string #interface { get; set; }
public string friendlyiface { get; set; }
public string friendlyifdescr { get; set; }
public string name { get; set; }
public string attribute { get; set; }
public bool isdefaultgw { get; set; }
public string monitor { get; set; }
public string descr { get; set; }
public string tiername { get; set; }
}
public class VPN_EUR_1
{
public string #interface { get; set; }
public string gateway { get; set; }
public string name { get; set; }
public string weight { get; set; }
public string ipprotocol { get; set; }
public string interval { get; set; }
public string time_period { get; set; }
public string alert_interval { get; set; }
public string descr { get; set; }
public string data_payload { get; set; }
public string latencylow { get; set; }
public string latencyhigh { get; set; }
public string losslow { get; set; }
public string losshigh { get; set; }
public string loss_interval { get; set; }
public bool dynamic { get; set; }
public string monitor { get; set; }
public string friendlyiface { get; set; }
public string friendlyifdescr { get; set; }
public int attribute { get; set; }
public string tiername { get; set; }
}
public class Null4
{
public string name { get; set; }
public string #interface { get; set; }
public string ipprotocol { get; set; }
public string gateway { get; set; }
public string attribute { get; set; }
public string tiername { get; set; }
}
public class Null6
{
public string name { get; set; }
public string #interface { get; set; }
public string ipprotocol { get; set; }
public string gateway { get; set; }
public string attribute { get; set; }
public string tiername { get; set; }
}
public class VPN_EUR_1V6
{
public bool dynamic { get; set; }
public string ipprotocol { get; set; }
public object gateway { get; set; }
public string #interface { get; set; }
public string friendlyiface { get; set; }
public string friendlyifdescr { get; set; }
public string name { get; set; }
public string attribute { get; set; }
public string descr { get; set; }
public string tiername { get; set; }
}
public class Data
{
public GW_WAN_1 GW_WAN { get; set; }
public INT1_DHCP6 INT1_DHCP6 { get; set; }
public VPN_EUR_1 VPN_EUR_1 { get; set; }
public Null4 Null4 { get; set; }
public Null6 Null6 { get; set; }
public VPN_EUR_1V6 VPN_NL_VPNV6 { get; set; }
}
public class Root
{
public string status { get; set; }
public int code { get; set; }
public int #return { get; set; }
public string message { get; set; }
public Data data { get; set; }
}
The problem is in the gateways variable, all of the properties are null. I think because of how the JSON is structured in the response, it might not be possible in C#, but perhaps there's another way of going about it?
The API for the firewall is here:
https://github.com/jaredhendrickson13/pfsense-api
Thanks
I am new to C# with JSON. I would like to select with Nvidia API, the "featuredProduct" part, but I have an error
Cannot access child value on Newtonsoft.Json.Linq.JProperty.
This code works for the "searchedProducts" part.
Can you explain to me why?
const string url = "";
const int refresh = 3000;
string json = getGpuFromNvidia(url);
var jsonParse = JObject.Parse(json);
var result = jsonParse["searchedProducts"]["featuredProduct"]
.Where(n => n["isFounderEdition"].Value<bool>() == true)
.Select(p => new CarteGraphique
{
displayName = (string)p["displayName"],
prdStatus = (string)p["prdStatus"],
directPurchaseLink = (string)p["retailers"][0]["directPurchaseLink"]
})
.ToList();
I tested this code in VS
string json = ...your code
var jsonObj = JsonConvert.DeserializeObject<NvidiaRoot>(json);
var result = jsonObj.searchedProducts.productDetails
.Where(n => n.isFounderEdition)
.Select(p => new
{
displayName = p.displayName,
prdStatus = p.prdStatus,
directPurchaseLink = p.retailers[0].directPurchaseLink
})
.ToList();
OUTPUT
[
{
"displayName": "NVIDIA RTX 3090",
"prdStatus": "out_of_stock",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB89455870.html"
},
{
"displayName": "NVIDIA RTX 3070",
"prdStatus": "out_of_stock",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB74221588.html"
},
{
"displayName": "NVIDIA RTX 3060 Ti",
"prdStatus": "out_of_stock",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB54012144.html"
},
{
"displayName": "NVIDIA RTX 3070 Ti",
"prdStatus": "out_of_stock",
"directPurchaseLink": null
},
{
"displayName": "NVIDIA RTX 3080 Ti",
"prdStatus": "out_of_stock",
"directPurchaseLink": null
}
]
UPDATE
if you need just a feature product
var featuredProduct = jsonObj.searchedProducts.featuredProduct;
var result = new
{
displayName = featuredProduct.displayName,
prdStatus = featuredProduct.prdStatus,
directPurchaseLink = featuredProduct.retailers[0].directPurchaseLink
};
Short OUTPUT
{
"displayName": "NVIDIA RTX 3080",
"prdStatus": "out_of_stock",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB15921567.html"
}
Full OUTPUT
var result = jsonObj.searchedProducts.featuredProduct;
{
"displayName": "NVIDIA RTX 3080",
"totalCount": 1,
"productID": 30045,
"imageURL": "https://assets.nvidia.partners/images/png/nvidia-geforce-rtx-3080.png",
"productTitle": "NVIDIA GEFORCE RTX 3080",
"digitialRiverID": "",
"productSKU": "NVGFT080",
"productUPC": "NVGFT080_FR",
"productUPCOriginal": "NVGFT080",
"productPrice": "€719.00",
"productAvailable": false,
"productRating": null,
"customerReviewCount": null,
"isFounderEdition": true,
"isFeaturedProduct": true,
"certified": false,
"manufacturer": "NVIDIA",
"locale": "FR",
"isFeaturedProdcutFoundInSecondSearch": false,
"category": "GPU",
"gpu": "RTX 3080",
"purchaseOption": "",
"prdStatus": "out_of_stock",
"minShipDays": null,
"maxShipDays": null,
"shipInfo": null,
"isOffer": false,
"offerText": "",
"retailers": [
{
"productId": 30045,
"productTitle": "NVIDIA GEFORCE RTX 3080",
"logoUrl": "https://assets.nvidia.partners/logos/geforce/retailer-ldlc.png",
"isAvailable": true,
"salePrice": "719.00",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB15921567.html",
"purchaseLink": "https://www.ldlc.com/fiche/PB15921567.html",
"hasOffer": false,
"offerText": null,
"partnerId": "45",
"storeId": "45",
"upc": "NVGFT080_FR",
"sku": "NVGFT080",
"stock": 0,
"retailerName": "https://www.ldlc.com",
"type": 80
}
],
"productInfo": [
{
"name": "cooling_system",
"value": "Fan"
},
{
"name": "gpu_boost_clock_speed",
"value": "1.71 GHz"
},
{
"name": "gpu_memory_size",
"value": "10 GB"
}
],
"compareProductInfo": [
{
"name": "cooling_system",
"value": "Fan"
},
{
"name": "gpu_clock_speed",
"value": "1.44 GHz"
},
{
"name": "gpu_boost_clock_speed",
"value": "1.71 GHz"
},
{
"name": "gpu_memory_size",
"value": "10 GB"
}
]
}
classes
public class NvidiaRoot
{
public object categories { get; set; }
public List<Filter> filters { get; set; }
public object filterGroups { get; set; }
public object search { get; set; }
public string version { get; set; }
public List<Sort> sort { get; set; }
public Pagination pagination { get; set; }
public SearchedProducts searchedProducts { get; set; }
public Disclaimer disclaimer { get; set; }
}
public class FilterValue
{
public string dispValue { get; set; }
public object dispValueDesription { get; set; }
public object groupType { get; set; }
public int units { get; set; }
public bool #checked { get; set; }
public object imageURL { get; set; }
public bool isValidate { get; set; }
}
public class Filter
{
public string displayName { get; set; }
public string filterField { get; set; }
public string displayMaxValues { get; set; }
public string fieldType { get; set; }
public int? selectedMinRangeVal { get; set; }
public int? selectedMaxRangeVal { get; set; }
public int? defaultMinRangeVal { get; set; }
public int? defaultMaxRangeVal { get; set; }
public string unitsOfMeasure { get; set; }
public bool #checked { get; set; }
public object units { get; set; }
public List<FilterValue> filterValues { get; set; }
public string dataType { get; set; }
public bool showCount { get; set; }
public int filterDisplayOrder { get; set; }
}
public class Sort
{
public string displayName { get; set; }
public string value { get; set; }
public bool selected { get; set; }
}
public class Pagination
{
public int page { get; set; }
public int limit { get; set; }
public int totalRecords { get; set; }
public bool featuredProductIncludedInCount { get; set; }
}
public class Retailer
{
public int productId { get; set; }
public string productTitle { get; set; }
public string logoUrl { get; set; }
public bool isAvailable { get; set; }
public string salePrice { get; set; }
public string directPurchaseLink { get; set; }
public string purchaseLink { get; set; }
public bool hasOffer { get; set; }
public object offerText { get; set; }
public string partnerId { get; set; }
public string storeId { get; set; }
public string upc { get; set; }
public string sku { get; set; }
public int stock { get; set; }
public string retailerName { get; set; }
public int type { get; set; }
}
public class ProductInfo
{
public string name { get; set; }
public string value { get; set; }
}
public class CompareProductInfo
{
public string name { get; set; }
public string value { get; set; }
}
public class FeaturedProduct
{
public string displayName { get; set; }
public int totalCount { get; set; }
public int productID { get; set; }
public string imageURL { get; set; }
public string productTitle { get; set; }
public string digitialRiverID { get; set; }
public string productSKU { get; set; }
public string productUPC { get; set; }
public string productUPCOriginal { get; set; }
public string productPrice { get; set; }
public bool productAvailable { get; set; }
public object productRating { get; set; }
public object customerReviewCount { get; set; }
public bool isFounderEdition { get; set; }
public bool isFeaturedProduct { get; set; }
public bool certified { get; set; }
public string manufacturer { get; set; }
public string locale { get; set; }
public bool isFeaturedProdcutFoundInSecondSearch { get; set; }
public string category { get; set; }
public string gpu { get; set; }
public string purchaseOption { get; set; }
public string prdStatus { get; set; }
public object minShipDays { get; set; }
public object maxShipDays { get; set; }
public object shipInfo { get; set; }
public bool isOffer { get; set; }
public string offerText { get; set; }
public List<Retailer> retailers { get; set; }
public List<ProductInfo> productInfo { get; set; }
public List<CompareProductInfo> compareProductInfo { get; set; }
}
public class ProductDetail
{
public string displayName { get; set; }
public int totalCount { get; set; }
public int productID { get; set; }
public string imageURL { get; set; }
public string productTitle { get; set; }
public string digitialRiverID { get; set; }
public string productSKU { get; set; }
public string productUPC { get; set; }
public string productUPCOriginal { get; set; }
public string productPrice { get; set; }
public bool productAvailable { get; set; }
public object productRating { get; set; }
public object customerReviewCount { get; set; }
public bool isFounderEdition { get; set; }
public bool isFeaturedProduct { get; set; }
public bool certified { get; set; }
public string manufacturer { get; set; }
public string locale { get; set; }
public bool isFeaturedProdcutFoundInSecondSearch { get; set; }
public string category { get; set; }
public string gpu { get; set; }
public string purchaseOption { get; set; }
public string prdStatus { get; set; }
public object minShipDays { get; set; }
public object maxShipDays { get; set; }
public object shipInfo { get; set; }
public bool isOffer { get; set; }
public string offerText { get; set; }
public List<Retailer> retailers { get; set; }
public List<ProductInfo> productInfo { get; set; }
public List<CompareProductInfo> compareProductInfo { get; set; }
}
public class SearchedProducts
{
public int totalProducts { get; set; }
public bool featuredProductIncludedInCount { get; set; }
public bool featuredProductsFlag { get; set; }
public FeaturedProduct featuredProduct { get; set; }
public List<ProductDetail> productDetails { get; set; }
public List<object> suggestedProductDetails { get; set; }
}
public class Disclaimer
{
public string text { get; set; }
}
You can try the below code.
To get the Featured Product. Sample Working code Here
var jsonParse = JObject.Parse(json);
var featuredProduct = jsonParse["searchedProducts"]["featuredProduct"];
var f = new CarteGraphique
{
displayName = featuredProduct["displayName"].ToString(),
prdStatus = featuredProduct["prdStatus"].ToString(),
directPurchaseLink = featuredProduct["retailers"][0]["directPurchaseLink"].ToString()
};
Console.WriteLine("Featured Product Details : " + f.displayName + ", " + f.prdStatus + ", " + f.directPurchaseLink);
I have this Json:
{
"trades": [
{
"id": "4004",
"instrument": "EUR_USD",
"price": "1.08938",
"openTime": "2020-02-26T12:15:32.309973340Z",
"initialUnits": "1",
"initialMarginRequired": "0.0363",
"state": "OPEN",
"currentUnits": "1",
"realizedPL": "0.0000",
"financing": "0.0000",
"dividendAdjustment": "0.0000",
"unrealizedPL": "-0.0026",
"marginUsed": "0.0362",
"takeProfitOrder": {
"id": "4005",
"createTime": "2020-02-26T12:15:32.309973340Z",
"type": "TAKE_PROFIT",
"tradeID": "4004",
"price": "1.09099",
"timeInForce": "GTC",
"triggerCondition": "DEFAULT",
"state": "PENDING"
}
}
],
"lastTransactionID": "4010"
}
And Classes:
public class TakeProfitOrder
{
public string id { get; set; }
public string createTime { get; set; }
public string type { get; set; }
public string tradeID { get; set; }
public string price { get; set; }
public string timeInForce { get; set; }
public string triggerCondition { get; set; }
public string state { get; set; }
}
public class Trade
{
public string id { get; set; }
public string instrument { get; set; }
public string price { get; set; }
public string openTime { get; set; }
public string initialUnits { get; set; }
public string initialMarginRequired { get; set; }
public string state { get; set; }
public string currentUnits { get; set; }
public string realizedPL { get; set; }
public string financing { get; set; }
public string dividendAdjustment { get; set; }
public string unrealizedPL { get; set; }
public string marginUsed { get; set; }
public TakeProfitOrder takeProfitOrder { get; set; }
}
public class RootObject
{
public List<Trade> trades { get; set; }
public string lastTransactionID { get; set; }
}
I deserialize with :
var result = JsonConvert.DeserializeObject<RootObject>(Json);
var price = result.trades.Select(p => p.price).ToList();
price.ForEach(Console.WriteLine);
It works. I can access "price" in "trades", but I do not know how to access the "price" in "takeProfitOrder". I need the value of "price" from "takeProfitOrder" in to a list. I am sure it is something very simple but I cannot figure out how to do it, even after looking at some similar examples.
Can somebody please help me?
It's simple
result.trades.Select(p => p.takeProfitOrder.price)
You should understand better from this example
foreach (Trade trade in result.trades)
{
TakeProfitOrder takeProfitOrder = trade.takeProfitOrder;
Console.WriteLine(takeProfitOrder.price);
}
what would the C# class definition look like to represent this JSON data?
{
"accountId": "101",
"website": "www.example.com",
"alternateWebsites": [
{
"website": "site2.example.com"
}
],
"email": "contact#mysite.com",
"alternateEmails": [
{
"email": "sales#example.com"
}
],
"address": {
"street": "234 Main Street",
"city": "San Diego",
"postalCode": "92101",
"state": "CA"
},
"rankingKeywords":
[{
"keyword": "Coffee",
"localArea": "Sacramento, CA"
}]
}
You can use a site like this http://jsonutils.com/
where you paste in your json and it constructs your classes for you. The result of your JSON produced...
public class AlternateWebsite
{
public string website { get; set; }
}
public class AlternateEmail
{
public string email { get; set; }
}
public class Address
{
public string street { get; set; }
public string city { get; set; }
public string postalCode { get; set; }
public string state { get; set; }
}
public class RankingKeyword
{
public string keyword { get; set; }
public string localArea { get; set; }
}
public class Root
{
public string accountId { get; set; }
public string website { get; set; }
public IList<AlternateWebsite> alternateWebsites { get; set; }
public string email { get; set; }
public IList<AlternateEmail> alternateEmails { get; set; }
public Address address { get; set; }
public IList<RankingKeyword> rankingKeywords { get; set; }
}
You could convert this with a service like http://json2csharp.com/. Enter the JSON and it will spit out C# model classes. Then, add them either as a class, or using Entity Framework (depending on your objective) into your project.
C# version:
public class AlternateWebsite
{
public string website { get; set; }
}
public class AlternateEmail
{
public string email { get; set; }
}
public class Address
{
public string street { get; set; }
public string city { get; set; }
public string postalCode { get; set; }
public string state { get; set; }
}
public class RankingKeyword
{
public string keyword { get; set; }
public string localArea { get; set; }
}
public class RootObject
{
public string accountId { get; set; }
public string website { get; set; }
public List<AlternateWebsite> alternateWebsites { get; set; }
public string email { get; set; }
public List<AlternateEmail> alternateEmails { get; set; }
public Address address { get; set; }
public List<RankingKeyword> rankingKeywords { get; set; }
}
I have some json like this:
{
"status": "OK",
"result": {
"#type": "address_result__201301",
"barcode": "1301013030001010212212333002003031013",
"bsp": "044",
"dpid": "99033785",
"postcode": "4895",
"state": "QLD",
"suburb": "COOKTOWN",
"city": null,
"country": "AUSTRALIA"
},
"search_date": "03-12-2014 15:31:03",
"search_parameters": {},
"time_taken": 636,
"transaction_id": "f8df8791-531e-4043-9093-9f35881f6bb9",
"root_transaction_id": "a1fa1426-b973-46ec-b61b-0fe5518033de"
}
Then I created some classes:
public class Address
{
public string status { get; set; }
public Result results { get; set; }
public string search_date { get; set; }
public SearchParameters search_parameters { get; set; }
public int time_taken { get; set; }
public string transaction_id { get; set; }
public string root_transaction_id { get; set; }
}
public class Result
{
public string #type { get; set; }
public string barcode { get; set; }
public string bsp { get; set; }
public string dpid { get; set; }
public string postcode { get; set; }
public string state { get; set; }
public string suburb { get; set; }
public string city { get; set; }
public string country { get; set; }
}
public class SearchParameters
{
}
Finally, I use these code to get Json data:
string result = "Above json";
JavaScriptSerializer json = new JavaScriptSerializer();
Address add = json.Deserialize<Address>(result);
I see that, add.status, add.search_date... etc have values, but add.results is null.
What is wrong with my code?
I think the issue is using #type as illegal identifier. Try using [DataMember(Name = "#type")] before public string #type { get; set; }. Add a [DataContract] before public class Address.
Hence, your final code will be,
[DataContract]
public class Result
{
[DataMember(Name = "#type")]
public string #type { get; set; }
public string barcode { get; set; }
public string bsp { get; set; }
public string dpid { get; set; }
public string postcode { get; set; }
public string state { get; set; }
public string suburb { get; set; }
public string city { get; set; }
public string country { get; set; }
}