Convert an List<object>to user defined class - c#

I have some data that is object IEnumerable, how to do I convert it into class type, the name of class is option
"option": {
"id": 8204,
"name": "250 ML",
"price": 40.0,
"status": 1,
"archive": 0
}
"option": {
"id": 8204,
"name": "250 ML",
"price": 40.0,
"status": 1,
"archive": 0
}
class Option
{
public long Id { get; set; }
public string Name { get; set; }
public long Price { get; set; }
public long Status { get; set; }
public long Archive { get; set; }
}
so far tried =>
foreach (var VARIABLE_3 in (IEnumerable) VARIABLE_2)
{
if ( VARIABLE_3.ToString().Contains("option") && !VARIABLE_3.ToString().Contains("options"))
{
object[] values = ((IEnumerable)VARIABLE_3).Cast<object>().ToArray();
//Option[] values = VARIABLE_3.ToString().Cast<Option>().ToArray();
foreach (var VARIABLE in values)
{
strStringBuilder.Append("VARIABLE: " + VARIABLE + "\n");
}
}
}

Use JavascriptSerializer or Json.Net serializer to serialize or deserialize Json string.
string jsonArrayObject = #"
[
{ "id": 8204,
"name": "250 ML",
"price": 40.0,
"status": 1,
"archive": 0
},
{
"id": 8208,
"name": "Coke",
"price": 0.0,
"status": 1,
"archive": 0
}
]";
Javascript Serializer
List<Option> optionList = new System.Web.Script.Serialization.
JavaScriptSerializer().Deserialize<List<Option>>(jsonArrayObject);
Json.Net
List<Option> optionList = JsonConvert.DeserializeObject<List<Option>>(jsonArrayObject);

Related

How to parse SQL JSON string in C# in asp.net mvc web api?

I have created web api in asp.net mvc where I am calling usp_JsonPract this SP which is returning JSON string from DB, Now I am facing problem to convert this string on .net mvc web api.
My stored procedure code:
Create proc [dbo].[usp_JsonPract]
as
BeginSelect category title
,[data] = JSON_QUERY(
(
select din.dishId,din.dishName,din.dishPrice,din.dishImage, din.dishType,
JSON_QUERY(dishPriceAndSize, '$.dishPriceAndSize') AS dishPriceAndSize,
JSON_QUERY(JAddOns, '$.addOns') AS addOns,
din.includedEggs, din.dishDescription, din.rating, din.review,din.discount
from DishMaster din
where din.category = dout.category
--and dishId in ( 11, 12,13 , 7 )
for json path
,INCLUDE_NULL_VALUES
)
)from DishMaster dout
group by category
for json path,without_array_wrapper
Stored procedure is returing JSON string that I want to pass to the client. I am using JsonConvert.DeserializeObject(jsonstr); to convert.
My C# code:
public object SQLJSONPract()
{
string jsonstr = string.Empty;
object o;
try
{
cmd.CommandText = "usp_JsonPract";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
var d = ds.Tables[0].Rows[0][0];
jsonstr = d.ToString();
object a = JsonConvert.DeserializeObject(jsonstr);
return (object)a;
}
catch (Exception ex)
{
return ex.Message;
}
}
Gives exception as below:
"Unterminated string. Expected delimiter: ". Path 'userDetails[2].data[1].addOns[1].name', line 59, position 3."
Result sample JSON is like this:
{
"title": "Rice",
"data": [
{
"dishId": 11,
"dishName": "stream rice",
"dishPrice": 40.0,
"dishImage": "streamrice.jpg",
"dishType": "VEG",
"dishPriceAndSize": [
{
"size": "Half",
"price": 90
},
{
"size": "Full",
"price": 180
}
],
"addOns": [
{
"name": "Extrachess",
"price": 25
},
{
"name": "Chess",
"price": 20
}
],
"includedEggs": false,
"dishDescription": "stream rice is delicious in test",
"rating": 4.5,
"review": "GOOD",
"discount": 20
},
{
"dishId": 12,
"dishName": "stream rice",
"dishPrice": 40.0,
"dishImage": "streamrice.jpg",
"dishType": "VEG",
"dishPriceAndSize": [
{
"size": "Half",
"price": 90
},
{
"size": "Full",
"price": 180
}
],
"addOns": [
{
"name": "Extrachess",
"price": 25
},
{
"name": "Chess",
"price": 20
}
],
"includedEggs": false,
"dishDescription": "stream rice is delicious in test",
"rating": 4.5,
"review": "GOOD",
"discount": 20
},
{
"dishId": 13,
"dishName": "stream rice",
"dishPrice": 40.0,
"dishImage": "streamrice.jpg",
"dishType": "VEG",
"dishPriceAndSize": [
{
"size": "Half",
"price": 90
},
{
"size": "Full",
"price": 180
}
],
"addOns": [
{
"name": "Extrachess",
"price": 25
},
{
"name": "Chess",
"price": 20
}
],
"includedEggs": false,
"dishDescription": "stream rice is delicious in test",
"rating": 4.5,
"review": "GOOD",
"discount": 20
},
{
"dishId": 7,
"dishName": "Chicken Biryani",
"dishPrice": 160.0,
"dishImage": "ChickenBiryani.jpg",
"dishType": "NonVEG",
"dishPriceAndSize": [
{
"size": "Half",
"price": 90
},
{
"size": "Full",
"price": 180
}
],
"addOns": [
{
"name": "Extrachess",
"price": 25
},
{
"name": "Chess",
"price": 20
}
],
"includedEggs": false,
"dishDescription": "Special Chicken Biryani For Our Valued Guest",
"rating": 4.5,
"review": "GOOD",
"discount": 20
}
]}
If any other suggestion for achieving this. Kindly suggest.
Make a file called JsonPract.cs and paste the following classes, in order to create several class that can be mapped to the json that you post in the question:
public class JsonPract
{
public string title { get; set; }
public List<Datum> data { get; set; }
}
public class DishPriceAndSize
{
public string size { get; set; }
public int price { get; set; }
}
public class AddOn
{
public string name { get; set; }
public int price { get; set; }
}
public class Datum
{
public int dishId { get; set; }
public string dishName { get; set; }
public double dishPrice { get; set; }
public string dishImage { get; set; }
public string dishType { get; set; }
public List<DishPriceAndSize> dishPriceAndSize { get; set; }
public List<AddOn> addOns { get; set; }
public bool includedEggs { get; set; }
public string dishDescription { get; set; }
public double rating { get; set; }
public string review { get; set; }
public int discount { get; set; }
}
Then you can deserialize your object as:
JsonPract myDeserializedClass = JsonConvert.DeserializeObject<JsonPract>(myJsonResponse);
For example:
public JsonPract SQLJSONPract()
{
string jsonstr = string.Empty;
object o;
try
{
cmd.CommandText = "usp_JsonPract";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
var d = ds.Tables[0].Rows[0][0];
jsonstr = d.ToString();
JsonPract a = JsonConvert.DeserializeObject<JsonPract>(jsonstr);
return a;
}
catch (Exception ex)
{
throw ex;
}
}

How to deserialise JSON from HubSpot

I am having trouble deserializing JSON received from HubSpot ContactList API.
I am using Restsharp and NewtonSoft, and I'm having real struggles understanding how to correctly define the required classes in order to deserialize the JSON string, which is below:
"contacts": [
{
"vid": 2251,
"portal-id": 5532227,
"is-contact": true,
"profile-url": "https://app.hubspot.com/contacts/5532227/contact/2251",
"properties": {
"firstname": {
"value": "Carl"
},
"lastmodifieddate": {
"value": "1554898386040"
},
"company": {
"value": "Cygnus Project"
},
"lastname": {
"value": "Swann"
}
},
"form-submissions": [],
"identity-profiles": [
{
"vid": 2251,
"saved-at-timestamp": 1553635648634,
"deleted-changed-timestamp": 0,
"identities": [
{
"type": "EMAIL",
"value": "cswann#cygnus.co.uk",
"timestamp": 1553635648591,
"is-primary": true
},
{
"type": "LEAD_GUID",
"value": "e2345",
"timestamp": 1553635648630
}
]
}
],
"merge-audits": []
},
{
"vid": 2301,
"portal-id": 5532227,
"is-contact": true,
"profile-url": "https://app.hubspot.com/contacts/5532227/contact/2301",
"properties": {
"firstname": {
"value": "Carlos"
},
"lastmodifieddate": {
"value": "1554886333954"
},
"company": {
"value": "Khaos Control"
},
"lastname": {
"value": "Swannington"
}
},
"identity-profiles": [
{
"vid": 2301,
"saved-at-timestamp": 1553635648733,
"deleted-changed-timestamp": 0,
"identities": [
{
"type": "EMAIL",
"value": "cswann#khaoscontrol.com",
"timestamp": 1553635648578,
"is-primary": true
},
{
"type": "LEAD_GUID",
"value": "c7f403ba",
"timestamp": 1553635648729
}
]
}
],
"merge-audits": []
}
],
"has-more": false,
"vid-offset": 2401
}
If I simply request the vid, I correctly get 2 vid's back. It's when I try to do the properties and that i get a fail.
Please help
Lets reduce the Json to the minimum to reproduce your error :
{
"vid": 2301,
"portal-id": 5532227,
"is-contact": true,
"profile-url": "https://app.hubspot.com/contacts/5532227/contact/2301",
"properties": {
"firstname": {
"value": "Carlos"
},
"lastmodifieddate": {
"value": "1554886333954"
},
"company": {
"value": "Khaos Control"
},
"lastname": {
"value": "Swannington"
}
}
}
And the appropriate class ContactListAPI_Result:
public partial class ContactListAPI_Result
{
[JsonProperty("vid")]
public long Vid { get; set; }
[JsonProperty("portal-id")]
public long PortalId { get; set; }
[JsonProperty("is-contact")]
public bool IsContact { get; set; }
[JsonProperty("profile-url")]
public Uri ProfileUrl { get; set; }
[JsonProperty("properties")]
public Dictionary<string, Dictionary<string, string>> Properties { get; set; }
}
public partial class ContactListAPI_Result
{
public static ContactListAPI_Result FromJson(string json)
=> JsonConvert.DeserializeObject<ContactListAPI_Result>(json);
//public static ContactListAPI_Result FromJson(string json)
// => JsonConvert.DeserializeObject<ContactListAPI_Result>(json, Converter.Settings);
}
public static void toto()
{
string input = #" {
""vid"": 2301,
""portal-id"": 5532227,
""is-contact"": true,
""profile-url"": ""https://app.hubspot.com/contacts/5532227/contact/2301"",
""properties"": {
""firstname"": {
""value"": ""Carlos""
},
""lastmodifieddate"": {
""value"": ""1554886333954""
},
""company"": {
""value"": ""Khaos Control""
},
""lastname"": {
""value"": ""Swannington""
}
}
}";
var foo = ContactListAPI_Result.FromJson(input);
}
But the Value of one property will be burrow in the sub dictionary, we can the project the object in a more usefull one :
public partial class ItemDTO
{
public long Vid { get; set; }
public long PortalId { get; set; }
public bool IsContact { get; set; }
public Uri ProfileUrl { get; set; }
public Dictionary<string, string> Properties { get; set; }
}
Adding the projection to the Class:
public ItemDTO ToDTO()
{
return new ItemDTO
{
Vid = Vid,
PortalId = PortalId,
IsContact = IsContact,
ProfileUrl = ProfileUrl,
Properties =
Properties.ToDictionary(
p => p.Key,
p => p.Value["value"]
)
};
}
Usage :
var result = foo.ToDTO();
Live Demo
Creating and managing class structure for big and nested key/value pair json is tedious task
So one approach is to use JToken instead.
You can simply parse your JSON to JToken and by querying parsed object, you will easily read the data that you want without creating class structure for your json
From your post it seems you need to retrieve vid and properties from your json so try below code,
string json = "Your json here";
JToken jToken = JToken.Parse(json);
var result = jToken["contacts"].ToObject<JArray>()
.Select(x => new
{
vid = Convert.ToInt32(x["vid"]),
properties = x["properties"].ToObject<Dictionary<string, JToken>>()
.Select(y => new
{
Key = y.Key,
Value = y.Value["value"].ToString()
}).ToList()
}).ToList();
//-----------Print the result to console------------
foreach (var item in result)
{
Console.WriteLine(item.vid);
foreach (var prop in item.properties)
{
Console.WriteLine(prop.Key + " - " + prop.Value);
}
Console.WriteLine();
}
Output:

Getting error deserialising JSON to List<T>

I want to deserialize this json to a List of Product objects but i get this error:
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ShoppingList.Product]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
This is my code:
{
"records": [
{
"id": "60",
"name": "Rolex Watch",
"description": "Luxury watch.",
"price": "25000",
"category_id": "1",
"category_name": "Fashion"
},
{
"id": "48",
"name": "Bristol Shoes",
"description": "Awesome shoes.",
"price": "999",
"category_id": "5",
"category_name": "Movies"
},
{
"id": "42",
"name": "Nike Shoes for Men",
"description": "Nike Shoes",
"price": "12999",
"category_id": "3",
"category_name": "Motors"
}
]
}
public class Product
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public decimal price { get; set; }
public int category_id { get; set; }
public string category_name { get; set; }
}
public async Task<List<Product>> GetProductsAsync()
{
Products = new List<Product>();
var uri = new Uri("https://hostname/api/product/read.php");
try
{
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Products = JsonConvert.DeserializeObject<List<Product>>(content);
}
}
catch (Exception )
{
throw;
}
return Products;
}
Your Json is not a List<Product>, its an object with a single property called records which is a List<Product>.
So your actual C# model is this:
public class RootObject
{
public List<Product> records { get; set; }
}
And you deserialize like this:
RootObject productsRoot = JsonConvert.DeserializeObject<RootObject>(content);
The issue is that your response JSON you've provided is an object which contains a list, but you are trying to deserialize the data into a straight list. I think all you need to do is add a second class which contains the list into your code, then deserialize using that list.
public class Product
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public decimal price { get; set; }
public int category_id { get; set; }
public string category_name { get; set; }
}
public class RootProduct
{
public List<Product> Products {get;set;}
}
Then you change your deserialization portion from List to
RootProduct response = JsonConvert.DeserializeObject<RootProduct>(content);
The usage would then simply be products. response.Products to access the list of items.
The problem is your json structure. Below is an example of a json array - notice i removed the property "records".
[
{
"id": "60",
"name": "Rolex Watch",
"description": "Luxury watch.",
"price": "25000",
"category_id": "1",
"category_name": "Fashion"
},
{
"id": "48",
"name": "Bristol Shoes",
"description": "Awesome shoes.",
"price": "999",
"category_id": "5",
"category_name": "Movies"
},
{
"id": "42",
"name": "Nike Shoes for Men",
"description": "Nike Shoes",
"price": "12999",
"category_id": "3",
"category_name": "Motors"
}
]
Given this data
[
{
"id": "60",
"name": "Rolex Watch",
"description": "Luxury watch.",
"price": "25000",
"category_id": "1",
"category_name": "Fashion"
},
{
"id": "48",
"name": "Bristol Shoes",
"description": "Awesome shoes.",
"price": "999",
"category_id": "5",
"category_name": "Movies"
},
{
"id": "42",
"name": "Nike Shoes for Men",
"description": "Nike Shoes",
"price": "12999",
"category_id": "3",
"category_name": "Motors"
}
]
And this class definition
public class Order
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public string price { get; set; }
public string category_id { get; set; }
public string category_name { get; set; }
}
The code to convert it from JSON to a C# List<Order> is:
public static List<Order> Map(string json)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<Order>>(json);
}

Converting JSON object to dictionary

I'm calling the ethplorer.io api, and it returns the below json. I have generated the classes in visual studio via 'paste special -> paste json as classes'. My problem is that Tokeninfo declares price as an object, this is because it can either be false if it has no price information, or a dictionary if it has values. While I have successfully deserialised the response using JsonConvert.DeserializeObject(rawJSON), I’m struggling to convert price in to c# dictionary if it has values.
public class Tokeninfo
{
public string address { get; set; }
public string name { get; set; }
public object decimals { get; set; }
public string symbol { get; set; }
public string totalSupply { get; set; }
public string owner { get; set; }
public long lastUpdated { get; set; }
public int issuancesCount { get; set; }
public int holdersCount { get; set; }
public object price { get; set; }
public string description { get; set; }
public float totalIn { get; set; }
public float totalOut { get; set; }
}
JSON response:
{
"address": "0xd8f41f341afe2c411b21b3f96263c6584b69baeb", //Not my address
"ETH": {
"balance": 762.13611095505,
"totalIn": 1040.0907032491,
"totalOut": 277.954592294
},
"countTxs": 22,
"tokens": [
{
"tokenInfo": {
"address": "0x355a458d555151d3b27f94227960ade1504e526a",
"name": "StockChain Coin",
"decimals": "18",
"symbol": "SCC",
"totalSupply": "10000000000000000000000000000",
"owner": "0x",
"lastUpdated": 1524401998,
"issuancesCount": 0,
"holdersCount": 86520,
"price": {
"rate": "0.0531126",
"diff": 4.8,
"diff7d": 19.82,
"ts": "1524400762",
"marketCapUsd": null,
"availableSupply": null,
"volume24h": "622004.0",
"currency": "USD"
}
},
"balance": 5000000000000000000,
"totalIn": 0,
"totalOut": 0
},
{
"tokenInfo": {
"address": "0xb679afd97bcbc7448c1b327795c3ef226b39f0e9",
"name": "Win Last Mile",
"decimals": "6",
"symbol": "WLM",
"totalSupply": "2000000000000000",
"owner": "0x8e7a75d5e7efe2981ac06a2c6d4ca8a987a44492",
"lastUpdated": 1524362946,
"issuancesCount": 0,
"holdersCount": 10945,
"price": false
},
"balance": 66000000,
"totalIn": 0,
"totalOut": 0
},
{
"tokenInfo": {
"address": "0xae66d00496aaa25418f829140bb259163c06986e",
"name": "Super Wallet Token",
"decimals": "8",
"symbol": "SW",
"totalSupply": "8400000000000000",
"owner": "0xba051682e9dbc40730fcef4a374e3a57a0ce3eff",
"lastUpdated": 1524401948,
"issuancesCount": 0,
"holdersCount": 30276,
"price": false
},
"balance": 11567900,
"totalIn": 0,
"totalOut": 0
},
{
"tokenInfo": {
"address": "0x8e4fbe2673e154fe9399166e03e18f87a5754420",
"name": "Universal Bonus Token | t.me/bubbletonebot",
"decimals": "18",
"symbol": "UBT",
"totalSupply": "1150000000000000000000000",
"owner": "0xc2db6e5b96dd22d9870a5ca0909cceac6604e21d",
"lastUpdated": 1524393745,
"issuancesCount": 0,
"holdersCount": 99896,
"price": false
},
"balance": 10000000000000000000,
"totalIn": 0,
"totalOut": 0
}
]
}
You need a custom deserializer to do what you want. It should be straight forward though. Here is some code which checks if the price is not false and then turns it into a Dictionary<string, string>. This code makes the assumption that your root object is named RootObject:
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jsonObject = JObject.Load(reader);
var root = default(Rootobject);
// Let's go through each tokenInfo and check if price is not false
// so we can turn it into a dictionary.
foreach (var thisToken in root.tokens)
{
if (thisToken.tokenInfo.price.ToString() != "false")
{
thisToken.tokenInfo.price = JsonConvert.DeserializeObject<Dictionary<string, string>>(thisToken.tokenInfo.price.ToString());
}
}
serializer.Populate(jsonObject.CreateReader(), root);
return root;
}
Please see the full example here and search for ProfessionConverter in that link for the full class.
I think it is not very good approach to use false in cases when there is no price. If there is no price it should be something like "price" :{} or price element shouldn't be there at all. In other words, it is not good idea to mixup boolean object and dictionaty imho.
I think you can use provided by VisualStudio class where Price is an object. And you can create a custom serializer which will treat false as an null (or object with empty fields) along with standart deserialization mechanism.

CoinPayment GetExchangeRates Api Response Hnadling Issue

I am working on a Coinpayment.net api implementation.I am trying to get the CoinExhange Rates by Using GetExchangeRate Method, I am unable to Parese the Response. I want to get the list of all the coins rate but i dont know which response class i can use to and how for getting the list of response.
Following is the Implementation i tried.
string result = string.Empty;
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(_ApiReferenceLink);
var response = await client.GetAsync("GetExchangeRates");
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
ExchangeRatesResponse datalist = JsonConvert.DeserializeObject<ExchangeRatesResponse>(result);
return Json(new { Message = "Your Transaction Has Been Completed Successfully!" }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { ErrorMessage = "Your Transaction Has Not Been Completed. Try Again Later!" }, JsonRequestBehavior.AllowGet);
}
}
The above code dint gave me the response in object so that i can loop through and get the required coins price.
This is the responce that api will return to me i want to convert it to object so that i can access it using object.
{
"error": "ok",
"result": {
"BTC": {
"is_fiat": 0,
"rate_btc": "1.000000000000000000000000",
"last_update": "1375473661",
"tx_fee": "0.00100000",
"status": "online",
"name": "Bitcoin",
"confirms": "2",
"capabilities": [
"payments",
"wallet",
"transfers",
"convert"
]
},
"LTC": {
"is_fiat": 0,
"rate_btc": "0.018343387500000000000000",
"last_update": "1518463609",
"tx_fee": "0.00100000",
"status": "online",
"name": "Litecoin",
"confirms": "3",
"capabilities": [
"payments",
"wallet",
"transfers",
"convert"
]
},
"USD": {
"is_fiat": 1,
"rate_btc": "0.000114884285404190000000",
"last_update": "1518463609",
"tx_fee": "0.00000000",
"status": "online",
"name": "United States Dollar",
"confirms": "1",
"capabilities": []
},
"CAD": {
"is_fiat": 1,
"rate_btc": "0.000091601308947890000000",
"last_update": "1518463609",
"tx_fee": "0.00000000",
"status": "online",
"name": "Canadian Dollar",
"confirms": "1",
"capabilities": []
},
"MAID": {
"is_fiat": 0,
"rate_btc": "0.000049810000000000000000",
"last_update": "1518463609",
"tx_fee": "0.00000000",
"status": "online",
"name": "MaidSafeCoin",
"confirms": "2",
"capabilities": [
"payments",
"wallet"
]
},
"XMR": {
"is_fiat": 0,
"rate_btc": "0.028198593333333000000000",
"last_update": "1518463609",
"tx_fee": "0.01000000",
"status": "online",
"name": "Monero",
"confirms": "3",
"capabilities": [
"payments",
"wallet",
"transfers",
"dest_tag"
]
},
"LTCT": {
"is_fiat": 0,
"rate_btc": "1.000000000000000000000000",
"last_update": "1375473661",
"tx_fee": "0.00100000",
"status": "online",
"name": "Litecoin Testnet",
"confirms": "0",
"capabilities": [
"payments",
"wallet",
"transfers"
]
}
}
}
The Responce Object Class that i used is:
public class ExchangeRatesResponse
{
public List<ExchangeRateItem> ItemsList { get; set; }
}
public class ExchangeRateItem
{
public string is_fiat { get; set; }
public decimal rate_btc { get; set; }
public int last_update { get; set; }
public string name { get; set; }
public int Confirms { get; set; }
}
Any help would be greatlly appreciated.
Thanks
Your C# object's structure does not match the JSON. Nothing will ever deserialise to a List<> because the JSON contains only objects, and not arrays (with the exception of "capabilities", but you don't seem to be interested in that bit). result is a single object containing several properties such as BTC, LTC, USD etc. So you need to make something which matches that.
Off the top of my head (untested), this should be more like it:
public class ExchangeRatesResponse
public ExchangeRateResult result { get; set; }
public string error { get; set; }
}
public class ExchangeRateResult
{
public ExchangeRateItem BTC { get; set; }
public ExchangeRateItem LTC { get; set; }
public ExchangeRateItem USD { get; set; }
public ExchangeRateItem CAD { get; set; }
public ExchangeRateItem MAID { get; set; }
public ExchangeRateItem XMR { get; set; }
public ExchangeRateItem LTCT { get; set; }
}
public class ExchangeRateItem
{
public string is_fiat { get; set; }
public decimal rate_btc { get; set; }
public int last_update { get; set; }
public string name { get; set; }
public int confirms { get; set; }
}
You can parse through this using LINQ. Add the directive below to your class.
using System.Linq;
This method will return the list you were requesting.
public List<ExchangeRateItem> ParseAndReturnExchangeRateItemList(string jsonString)
{
//parse JSON and grab it's children.
var JSONobj = JObject.Parse(jsonString).Children();
//turn into dictionary of property name and value
var dictionary = JSONobj
.Select(s => (s as JProperty))
.ToDictionary(u => u.Name, v => v.Value);
var ExchangeRateToExchangeDetailsDictionary =
//grab result, maybe in another line grab error to make sure none exist.
dictionary["result"]
.Select(s => (s as JProperty))
.ToDictionary(u => u.Name
,v => JsonConvert.DeserializeObject<ExchangeRateItem>(v.Value.ToString()));
//you iterate through your dictionary like this
foreach (var kvp in ExchangeRateToExchangeDetailsDictionary)
{
//this is just string key of the exchangeRateCode
var exchangeRate = kvp.Key;
//this will return the ExchangeRateItem object.
var exchangeRateDetails = kvp.Value;
}
//you can also get the ExchangeRateItem object per exchangeRate like this
var giveMeUSExchangeRate = ExchangeRateToExchangeDetailsDictionary["USD"];
//if you need to just return a list of ExchangeRateItem objects you can do this
List<ExchangeRateItem> listOfExchangeRateItem = ExchangeRateToExchangeDetailsDictionary.Values.ToList();
return listOfExchangeRateItem;
}
You can call it and feed it your JSON result.
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
ExchangeRatesResponse datalist = ParseAndReturnExchangeRateItem(result);
return Json(new { Message = "Your Transaction Has Been Completed Successfully!" }, JsonRequestBehavior.AllowGet);
}

Categories