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);
}
Related
I have a JSON object like below,
[
{
"BatchId": "BAT1",
"PartialBatch": [
{
"PartialBatchID": "PAR1",
"Status": "Active"
},
{
"PartialBatchID": "PAR2",
"Status": "Inactive"
}
]
},
{
"BatchId": "BAT2",
"PartialBatch": [
{
"PartialBatchID": "PAR3",
"Status": "Active"
},
{
"PartialBatchID": "PAR4",
"Status": "Inactive"
}
]
}
]
I have another Array of Strings of PartialBatchID's
["PAR1","PAR3"]
What would be the best and most quickiest way to update the status fields to Active for the PartialBatchID's present in above array, against the main json.
Here's a way using the Newtonsoft.Json Nuget package. Now in your example the PAR1 and PAR3 are already active, but this will work:
void Main()
{
var match = new [] { "PAR1", "PAR3"};
var json = JsonConvert.DeserializeObject<JsonData[]>(main);
foreach (var b in json.SelectMany(x => x.PartialBatch).Where(x => match.Contains(x.PartialBatchID)))
{
b.Status = "Active";
}
var modifiedJson = JsonConvert.SerializeObject(json);
}
public class JsonData
{
public string BatchId { get; set; }
public Batch[] PartialBatch { get; set; }
}
public class Batch
{
public string PartialBatchID { get; set; }
public string Status { get; set; }
}
const string main = #"
[
{
'BatchId': 'BAT1',
'PartialBatch': [
{
'PartialBatchID': 'PAR1',
'Status': 'Active'
},
{
'PartialBatchID': 'PAR2',
'Status': 'Inactive'
}
]
},
{
'BatchId': 'BAT2',
'PartialBatch': [
{
'PartialBatchID': 'PAR3',
'Status': 'Active'
},
{
'PartialBatchID': 'PAR4',
'Status': 'Inactive'
}
]
}
]";
So, I am trying to count the amount of values in JSON using c#. The Json is:
{
"Someid": 657442,
"roles": [
{
"id": 3892751,
"name": "Guest",
"rank": 0,
"memberCount": 0
},
{
"id": 3892750,
"name": "Fanz!<3",
"rank": 1,
"memberCount": 0
},
{
"id": 3892749,
"name": "Lead-Singer",
"rank": 254,
"memberCount": 0
},
{
"id": 3892748,
"name": "Drums",
"rank": 255,
"memberCount": 0
}
]
}
I want to count the amount "roles". The JSON is just in a string variable. Help?
You can either use like this:
var token = JToken.Parse(input);
var roles= token.Value<JArray>("roles");
var count = roles.Count;
Or you can also use JsonPath:
var token = JToken.Parse(input);
var count = token.SelectTokens("$.roles[*]").Count();
But ideally, you should be serilizing into an object and then using the properties to get the Count:
public class Role
{
public int id { get; set; }
public string name { get; set; }
public int rank { get; set; }
public int memberCount { get; set; }
}
public class MyObject
{
public int Someid { get; set; }
public List<Role> roles { get; set; }
}
var item = JsonConvert.DeserializeObject<MyObject>(input);
var count = item.roles.Count;
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);
{
"_id": "111de970-4f3f-4ae6-9d3b-396e60ff50aa",
"ClaimNumber": 111,
"Details": [
{
"Amount": "100",
"Types": [
{
"InvoiceType": "OO",
"Status": "N"
},
{
"InvoiceType": "PP",
"Status": "N"
}
]
},
{
"Amount": "100",
"Types": [
{
"InvoiceType": "OO",
"Status": "N"
},
{
"InvoiceType": "SS",
"Status": "N"
}
]
}
]
}
public class Type
{
public string InvoiceType { get; set; }
public string Status { get; set; }
}
public class Detail
{
public string Amount { get; set; }
public List<Type> Types { get; set; }
}
public class RootObject
{
public string _id { get; set; }
public int ClaimNumber { get; set; }
public List<Detail> Details { get; set; }
}
I Would like to update the values of Types array "Status" = "P" in the Details array when the "_id" column and "Types.InvoiceType" = "OO" value matches.
Please provide me an example on how to achieve in c# using mongo driver.
There you go:
var filter = Builders<RootObject>.Filter.Eq(o => o._id, "111de970-4f3f-4ae6-9d3b-396e60ff50aa");
var update = Builders<RootObject>.Update.Set($"{nameof(RootObject.Details)}.$[].{nameof(Detail.Types)}.$[elem].{nameof(Type.Status)}", "P");
var arrayFilter = new JsonArrayFilterDefinition<BsonDocument>($"{{ 'elem.{nameof(Type.InvoiceType)}': 'OO' }}");
var updateOptions = new UpdateOptions { ArrayFilters = new[] { arrayFilter } };
var result = new MongoClient()
.GetDatabase("database")
.GetCollection<RootObject>("collection")
.UpdateOne(filter, update, updateOptions);
I want to create JSON object with following format:-
{
"result": [
{
"name": "John",
"address": "US",
},
{
"name": "Josh",
"address": "Japan",
}
],
"error": [
{
"message": "error-message"
}
],
"success": [
{
"message": "success-message"
}
]
}
I have tried the following, but it doesn't help me.
dynamic record = new { result = new {name="", address=""},
error = new {message=""},
success = new {message=""} };
Update 1:-
Here is my code:-
List addressList = new List();
// Loop over items within the container and URI.
foreach (var item in items)
{
dynamic record = new { result = new object[] {
new {name = item.name, address = item.address} } };
addressList.Add(record);
}
Result:-
[ {
"result": [
{
"name": "John",
"address": "US"
}
]
},
{
"result": [
{
"name": "Jack",
"address": "CA"
}
]
}
]
Expected json result:-
[{
"result": [{
"name": "John",
"address": "US"
}]
},
{
"result": [{
"name": "Jack",
"address": "CA"
}],
"error": [{
"message": "error-message"
}],
"success": [{
"message": "success-message"
}]
}
]
How do I update my code to get above expected json result?
You...create arrays. You're not doing that. You're creating individual objects.
Something along the lines of:
dynamic record = new {
result = new object[] {
new {name = "John", address = "US"},
new {name = "Josh", address = "Japan"}
},
error = new object[] /*...*/,
success = new object[] /*...*/
};
If you want exactly JSON, then newtonsoft.Json makes it easier:
Json json = new Json();
json.result = new object[] {
new {name = "John", address = "US"},
new {name = "Josh", address = "Japan"}
};
// json.error = ... and so on
string output = JsonConvert.SerializeObject(product);
The output you will have is:
{
"result": [
{
"name": "John",
"address": "US",
},
{
"name": "Josh",
"address": "Japan",
}
],
"error": [
{
...
}
]
}
To deserialize it back, use:
Json deserializedJson = JsonConvert.DeserializeObject<Json>(output);
you are not creating an array
if you want to create JSON arrays from c# you have to use the following POCO
public class Result
{
public string name { get; set; }
public string address { get; set; }
}
public class Error
{
public string message { get; set; }
}
public class Success
{
public string message { get; set; }
}
public class RootObject
{
public List<Result> result { get; set; }
public List<Error> error { get; set; }
public List<Success> success { get; set; }
}
and then use Json.net
var json = JsonConvert.SerializeObject( "your instance of the root Object")
//You need to make this class structure first
public class Response
{
public List<Result> result { get; set; }
public List<Error> error { get; set; }
public List<Success> success { get; set; }
}
public class Result
{
public string name { get; set; }
public string address { get; set; }
}
public class Error
{
public string message { get; set; }
}
public class Success
{
public string message { get; set; }
}
// And then you can use it like this
var response = new Response()
{
result = new List<Result>
{
new Result() {name = "Jhon", address = "US"},
new Result() {name = "Jhon", address = "US"},
},
error = new List<Error>()
{
new Error() {message = "error-message 1"},
new Error() {message = "error-message 2"}
},
success = new List<Success>()
{
new Success(){message = "success-message 1"},
new Success(){message = "success-message 2"},
}
};
The Model Class
public class MegaMenu
{
public int department_id { get; set; }
public string department_name { get; set; }
public List<SectionListData> sectionListData { get; set; }
}
public class SectionListData
{
public int section_id { get; set; }
public string section_name { get; set; }
public List<ItemHeadList> itemHeadList { get; set; }
}
public class ItemHeadList
{
public int item_head_id { get; set; }
public string item_name { get; set; }
}
public class WrapperMegaMenu
{
public List<MegaMenu> megaMenuList { get; set; }
public string error { get; set; }
}
The Services
dept_result is the array of all department,section_result is the array of all section,Item_result is the array of all items
List<MegaMenu> listmenu = new List<MegaMenu>();
foreach (var each_dept in dept_result)
{
MegaMenu megaMenu = new MegaMenu();
megaMenu.department_id = each_dept.shopdepartment_id;
megaMenu.department_name = each_dept.name_en;
var temSectionList = section_result
.Where(item => item.shopdepartment_id == each_dept.shopdepartment_id).ToList().Select(sectionData => new SectionListData
{
section_id = sectionData.shopsection_id,
section_name = sectionData.name_en,
itemHeadList = Item_result.Where(itemHead => itemHead.shopsection_id == sectionData.shopsection_id).ToList().Select(itemHeadData => new ItemHeadList {
item_head_id = itemHeadData.item_head_id,
item_name = itemHeadData.name_en
}).ToList()
}).ToList();
megaMenu.sectionListData = temSectionList;
listmenu.Add(megaMenu);
}
//wrapperDept.departmentList = dept_result.ToList();
wrapper.megaMenuList = listmenu.ToList();
Result
{
"megaMenuList": [
{
"department_id": 71,
"department_name": "Baby's Hygiene",
"sectionListData": [
{
"section_id": 56,
"section_name": "Diapers",
"itemHeadList": []
},
{
"section_id": 57,
"section_name": "Wipes",
"itemHeadList": [
{
"item_head_id": 142,
"item_name": "Telivision"
}
]
}
]
}
]
}