i have an application that has to deserialize an array of data wrapped in a "results" Root Object, using Netwonsoft.Json package from NuGet
The Json string is exactly this:
{"results":[{"Coin":"SBD","LP":0.000269,"PBV":-54.36,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true},{"Coin":"XMR","LP":0.027135,"PBV":11.44,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true}]}
This Json string is created from a Console App i made, i wanted it to look like this https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=BTC-NEO&tickInterval=hour
My class looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp2
{
public class Result
{
public string Coins { get; set; }
public decimal LastPrice { get; set; }
public decimal PercentBuyVolume { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
}
In the Main form i have a function to download from a URL that Json (i have XAMPP running Apache) and deserialize it in an array. And it looks like this:
private void DownloadBittrexData()
{
int PanelID = 0;
var Coin = new List<string>();
var LastPrice = new List<decimal>();
var PercentBuyVolume = new List<decimal>();
var MACD1M = new List<bool>();
var MACD30M = new List<bool>();
var MACD1H = new List<bool>();
var MACD1D = new List<bool>();
var client = new WebClient();
var URL = client.DownloadString("http://localhost/test.json");
Console.WriteLine("Json String from URL: " + URL);
var dataDeserialized = JsonConvert.DeserializeObject<RootObject>(URL);
foreach (var data in dataDeserialized.results)
{
Coin.Add(data.Coins);
LastPrice.Add(data.LastPrice);
PercentBuyVolume.Add(data.PercentBuyVolume);
}
int sizeOfArrayClose = Coin.Count - 1;
for (int i = 0; i <= sizeOfArrayClose; i++)
{
Console.WriteLine("Coin: " + Coin[i]);
Console.WriteLine("Lastprice: " + LastPrice[i]);
Console.WriteLine("PBV: " + PercentBuyVolume[i]);
}
}
Newtonsoft.Json is of course declared at the beginning of the form together with System.Net
using System.Net;
using Newtonsoft.Json;
The output looks like this:
Json String from URL: {"results":[{"Coin":"SBD","LP":0.000269,"PBV":-54.36,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true},{"Coin":"XMR","LP":0.027135,"PBV":11.44,"MACD1M":true,"MACD30M":true,"MACD1H":true,"MACD1D":true}]}
Coin:
Lastprice: 0
PBV: 0
Coin:
Lastprice: 0
PBV: 0
It's like it fails to deserialize it after downloading it.
What should i do? Thank you very much.
Your property names don't map to the field names in the JSON. You could rename your C# properties to match the JSON, but it would make for unreadable downstream code.
Instead, you should map your properties (with nice, readable names) to the names that appear in the JSON, using JsonPropertyAttribute:
public class Result
{
public string Coin { get; set; } //didn't bother here: changed property name to Coin
[JsonProperty("LP")]
public decimal LastPrice { get; set; }
[JsonProperty("PBV")]
public decimal PercentBuyVolume { get; set; }
}
your model should be like this for deserialize json
public class Result
{
public string Coin { get; set; }
public double LP { get; set; }
public double PBV { get; set; }
public bool MACD1M { get; set; }
public bool MACD30M { get; set; }
public bool MACD1H { get; set; }
public bool MACD1D { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
LastPrice and PercentBuyVolume are not available in your model that's the reason it's getting an error.
I tried your exact code on my system and I was able to retrieve the result as expected. Hope this helps, It's easy to understand.
Here is the main class
static void Main(string[] args)
{
RootObject configfile = LoadJson();
foreach (var tResult in configfile.results)
{
Console.WriteLine("Coin: " + tResult.Coin);
Console.WriteLine("Lastprice: " + tResult.LP);
Console.WriteLine("PBV: " + tResult.PBV);
}
Console.ReadLine();
}
LoadJson Function would be
private static RootObject LoadJson()
{
string json = "{\"results\":[{\"Coin\":\"SBD\",\"LP\":0.000269,\"PBV\":-54.36,\"MACD1M\":true,\"MACD30M\":true,\"MACD1H\":true,\"MACD1D\":true},{\"Coin\":\"XMR\",\"LP\":0.027135,\"PBV\":11.44,\"MACD1M\":true,\"MACD30M\":true,\"MACD1H\":true,\"MACD1D\":true}]}";
RootObject configs = Deserialize<RootObject>(json);
return configs;
}
and Deserialize function would be
private static T Deserialize<T>(string json)
{
T unsecureResult;
string _DateTypeFormat = "yyyy-MM-dd HH:mm:ss";
DataContractJsonSerializerSettings serializerSettings = new DataContractJsonSerializerSettings();
DataContractJsonSerializer serializer;
MemoryStream ms;
unsecureResult = default(T);
serializerSettings.DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat(_DateTypeFormat);
serializer = new DataContractJsonSerializer(typeof(T));
ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
unsecureResult = (T)serializer.ReadObject(ms);
return unsecureResult;
}
and Now your Datamodel would be
public class Result
{
public string Coin { get; set; }
public double LP { get; set; }
public double PBV { get; set; }
public bool MACD1M { get; set; }
public bool MACD30M { get; set; }
public bool MACD1H { get; set; }
public bool MACD1D { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
Related
I am connecting to an external API which seems to be returning JSON
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances;
}
When I move over .Data.Balances, it shows:
IEnumerable<API.Net.Objects.Spot.SpotData.APIBalance>
API.Net.Objects.Spot.SpotData.APIAccountInfo.Balances { get; set; }
List of assets and their current balances
Here is an extract of the JSON data:
"balances":[
{
"asset":"ABC",
"free":"0.00000000",
"locked":"0.00000000"
},
{
"asset":"DEF",
"free":"0.00000000",
"locked":"0.00000000"
},
{
"asset":"GHI",
"free":"0.00000000",
"locked":"0.00000000"
}
]
How do I make use of this data so if I type console.writeline(data[0]["asset"]), it gives me ABC?
This seems to be the simplist solution:
using System.Linq;
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances.ToList();
Console.WriteLine(data[0].asset);
Console.WriteLine(data[0].free);
Console.WriteLine(data[0].locked);
}
Hy,
From the sample file you can create a class ´balance »
Public class balance
{
Public string asset {get; set;}
Public Free .......
Public Locked .....
}
And then you can use Json.net
To deserialize the JSon file
public void serializejson()
{
List balances = JsonConvert.DeserializeObject<List>(data);
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Game
{
public class Balance
{
[JsonPropertyName("asset")]
public string Asset { get; set; }
[JsonPropertyName("free")]
public string Free { get; set; }
[JsonPropertyName("locked")]
public string Locked { get; set; }
}
public class Root
{
[JsonPropertyName("balances")]
public List<Balance> Balances { get; set; }
}
class Program
{
static void Main(string[] args)
{
var data = File.ReadAllText("test.json");
var deserialized = JsonSerializer.Deserialize<Root>(data);
var balances = deserialized.Balances;
// Don't iterati in such a way! Use foreach instead.
for (int i = 0; i < balances.Count; i++)
{
Console.WriteLine($"{balances[i].Asset} {balances[i].Free} {balances[i].Locked}");
}
foreach (var balance in balances)
{
Console.WriteLine($"{balance.Asset} {balance.Free} {balance.Locked}");
}
}
}
}
You can use this code for you:
public class Balance {
public string asset { get; set; }
public string free { get; set; }
public string locked { get; set; }
}
public class Root {
public List<Balance> balances { get; set; }
}
And for deserialize:
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances;
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(data);
Console.WriteLine(myDeserializedClass.balances[0].asset);
}
i have the following class
using System;
public class AppEventsClass
{
public string title { get; set; }
public string description { get; set; }
}
after calling a remote webservice i retrive the following json string:
{"d":"[title\":\"test\",\"description\":\"test desc\"},{\"title\":\"test2\",\"description\":\"desc test 2\"}]"}
after retriving that json string, how can i convert the string in a List<> of AppEventsClass with Newtonsoft?
I tried several solutions, but nothing that works fine for me.
for example this:
List<AppEventsClass> result = new List<AppEventsClass>();
result = JsonConvert.DeserializeObject<List<AppEventsClass>>(content).ToList();
and this is the .asmx that serializes the string:
[ScriptMethod(UseHttpGet = true)]
public string GetEvents()
{
using (mySQLDataContext ctx = new secondosensoSQLDataContext())
{
List<eventi> eventiList = ctx.eventi.ToList();
List<AppEventsClass> eventiClassList = new List<AppEventsClass>();
for (int i = 0; i < eventiList.Count; i++)
{
AppEventsClass a = new AppEventsClass();
a.title = eventiList[i].titlolo_evento;
a.description = eventiList[i].descrizione_evento;
eventiClassList.Add(a);
}
var json = JsonConvert.SerializeObject(eventiClassList);
return json;
}
}
1st issues seems that the response we retrieve is not formed correctly
Assumed that the json string is looking like the following:
{"d":[{"title":"test","description":"test desc"},{"title":"test2","description":"desc test 2"}]}
The correct class for deserialization should look like this
public class Rootobject
{
public D[] d { get; set; }
}
public class D
{
public string title { get; set; }
public string description { get; set; }
}
Thanks
PS. Here is a working example:
class Program
{
static void Main(string[] args)
{
string json = "{\"d\":[{title:\"test\",description:\"test desc\"},{title:\"test2\",description:\"desc test 2\"}]}";
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(json);
}
}
public class Rootobject
{
public D[] d { get; set; }
}
public class D
{
public string title { get; set; }
public string description { get; set; }
}
I am looking to deserialize data and place it into a generic class from a response from Azure.
<ServiceResources xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/windowsazure">
<ServiceResource>
<Name>Airport1</Name>
<Type>Microsoft.SqlAzure.FirewallRule</Type>
<State>Normal</State>
<SelfLink>https://management.core.windows.net:xxx/xxx/services/sqlservers/servers/xxx/firewallrules/Airport1</SelfLink>
<ParentLink>https://management.core.windows.net:xxxx/services/sqlservers/servers/xxx</ParentLink>
<StartIPAddress>000.000.000.000</StartIPAddress>
<EndIPAddress>2000.000.000.000</EndIPAddress>
</ServiceResource>
There are several objects I need to deserialze into my class.
[Serializable, XmlRoot(ElementName = "ServiceResource", Namespace = "http://schemas.microsoft.com/windowsazure/")]
public class ServiceResource
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Type")]
public string Type { get; set; }
[XmlElement("State")]
public string State { get; set; }
[XmlElement("SelfLink")]
public string SelfLink { get; set; }
[XmlElement("ParentLink")]
public string ParentLink { get; set; }
[XmlElement("StartIPAddress")]
public string StartIPAddress { get; set; }
[XmlElement("EndIPAddress")]
public string EndIPAddress { get; set; }
}
I have tried several different ventures into this and can't nail it. I have used the xmlSerializer but hit blocks on that.
using (var responseStreamReader = new StreamReader(webResponse.GetResponseStream()))
{
XmlSerializer serializer = new XmlSerializer(typeof(ServiceResource));
ServiceResource deserialized = (ServiceResource)serializer.Deserialize(responseStreamReader);
}
Any help would be gratefully accepted.
Answer
The Azure REST Api is returning a list of ServiceResource in the XML. So you need to encapsulate that into a class. Here is an example.
[XmlRoot(
ElementName = "ServiceResources",
Namespace = "http://schemas.microsoft.com/windowsazure")]
public class ServiceResources
{
public ServiceResources()
{
Items = new List<ServiceResource>();
}
[XmlElement("ServiceResource")]
public List<ServiceResource> Items { get; set; }
}
public class ServiceResource
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Type")]
public string Type { get; set; }
[XmlElement("State")]
public string State { get; set; }
[XmlElement("SelfLink")]
public string SelfLink { get; set; }
[XmlElement("ParentLink")]
public string ParentLink { get; set; }
[XmlElement("StartIPAddress")]
public string StartIPAddress { get; set; }
[XmlElement("EndIPAddress")]
public string EndIPAddress { get; set; }
}
With those two classes, you can now do the following.
var response = request.GetResponse();
var message = string.Empty;
using (var responseStreamReader = new StreamReader(response.GetResponseStream()))
{
message = responseStreamReader.ReadToEnd();
}
var textReader = new StringReader(message);
var serializer = new XmlSerializer(typeof(ServiceResources));
var serviceResources =
serializer.Deserialize(textReader) as ServiceResources;
Demo Console App
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace DeserializeAzureXmlResponse
{
class Program
{
private static string certificateThumbprint = "19DAED4D4ABBE0D400DC33A6D99D00D7BBB24472";
private static string subscriptionId = "14929cfc-3501-48cf-a5c9-b24a7daaf694";
static string sqlServerName = "mvp2015";
static string managementUri = "https://management.core.windows.net";
static string sqlServerApi = "services/sqlservers/servers";
static string firewallRules = "firewallrules";
static void Main(string[] args)
{
var restUri = CreateRestUri();
var clientCert = GetX509FromPersonalStore();
var request = (HttpWebRequest)HttpWebRequest.Create(restUri);
request.Headers.Add("x-ms-version", "2012-03-01");
request.ClientCertificates.Add(clientCert);
var response = request.GetResponse();
var message = string.Empty;
using (var responseStreamReader = new StreamReader(response.GetResponseStream()))
{
message = responseStreamReader.ReadToEnd();
}
var textReader = new StringReader(message);
var serializer = new XmlSerializer(typeof(ServiceResources));
var serviceResources = serializer.Deserialize(textReader) as ServiceResources;
foreach (var sr in serviceResources.Items)
{
Console.WriteLine("Name".PadRight(20) + sr.Name);
Console.WriteLine("Type".PadRight(20) + sr.Type);
Console.WriteLine("State".PadRight(20) + sr.State);
Console.WriteLine("SelfLink".PadRight(20) + sr.SelfLink);
Console.WriteLine("ParentLink".PadRight(20) + sr.ParentLink);
Console.WriteLine("StartIP".PadRight(20) + sr.StartIPAddress);
Console.WriteLine("EndIP".PadRight(20) + sr.EndIPAddress);
Console.WriteLine("+++++++++++");
}
Console.ReadLine();
}
static Uri CreateRestUri()
{
// https://management.core.windows.net/{subscriptionID}/services/sqlservers/servers/{server}/firewallrules/
var builder = new StringBuilder();
builder.Append(managementUri + "/");
builder.Append(subscriptionId + "/");
builder.Append(sqlServerApi + "/");
builder.Append(sqlServerName + "/");
builder.Append(firewallRules + "/");
var uri = new Uri(builder.ToString());
return uri;
}
static X509Certificate GetX509FromPersonalStore()
{
// To view the personal store, press `Win + R` and then type `certmgr.msc`
var store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, true);
var certificate = certificates[0];
store.Close();
return certificate;
}
}
[XmlRoot(
ElementName = "ServiceResources",
Namespace = "http://schemas.microsoft.com/windowsazure")]
public class ServiceResources
{
public ServiceResources()
{
Items = new List<ServiceResource>();
}
[XmlElement("ServiceResource")]
public List<ServiceResource> Items { get; set; }
}
public class ServiceResource
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Type")]
public string Type { get; set; }
[XmlElement("State")]
public string State { get; set; }
[XmlElement("SelfLink")]
public string SelfLink { get; set; }
[XmlElement("ParentLink")]
public string ParentLink { get; set; }
[XmlElement("StartIPAddress")]
public string StartIPAddress { get; set; }
[XmlElement("EndIPAddress")]
public string EndIPAddress { get; set; }
}
}
Output
Name My-House
Type Microsoft.SqlAzure.FirewallRule
State Normal
SelfLink https://management.core.windows.net/14929cfc-35
ParentLink https://management.core.windows.net/14929cfc-35
StartIP 123.435.234.643
EndIP 123.435.234.643
+++++++++++
Name AllowAllWindowsAzureIps
Type Microsoft.SqlAzure.FirewallRule
State Normal
SelfLink https://management.core.windows.net/14929cfc-35
ParentLink https://management.core.windows.net/14929cfc-35
StartIP 0.0.0.0
EndIP 0.0.0.0
+++++++++++
See Also
Is it possible to deserialize XML into List<T>?
List Firewall Rules
I am assuming you are trying to deserialize the whole object graph. Given xml has root node ServiceResources which contains ServiceResource. You have two options, you can mimic the whole xml into classes and desrialize; or just get the inner node of ServiceResource and deserialize that part.
If you use first option, then you would need to store ServiceResource inside another class which has mapped collections property with XmlElement name set to "ServiceResource", e.g.:
[XmlType(Namespace="http://schemas.microsoft.com/windowsazure")]
[XmlRoot(Namespace="http://schemas.microsoft.com/windowsazure")]
public class ServiceResource
{
public string Name { get; set; }
public string Type { get; set; }
public string State { get; set; }
public string SelfLink { get; set; }
public string ParentLink { get; set; }
public string StartIPAddress { get; set; }
public string EndIPAddress { get; set; }
}
[XmlType(Namespace="http://schemas.microsoft.com/windowsazure")]
[XmlRoot(Namespace="http://schemas.microsoft.com/windowsazure")]
public class ServiceResources
{
[XmlElement("ServiceResource")]
public List<ServiceResource> ServiceResource { get; set; }
}
With that you should be able to deserialize directly. Container class has the collections mapped to the ServiceResource element, which will load all of the nodes for service resource. Note: deserialization target type is now "ServiceResources" not the inner type "ServiceResource"
using (var responseStreamReader = new StreamReader(webResponse.GetResponseStream()))
{
XmlSerializer serializer = new XmlSerializer(typeof(ServiceResources));
ServiceResources deserialized = (ServiceResources)serializer.Deserialize(responseStreamReader);
//you can access each item in loop
foreach(var res in deserialized.ServiceResource)
{
//access items e.g.
var name = res.Name;
}
}
I have a web api service that converts JSON object to a specific list:
here is the model class:
public class rest_all_data
{
public string RestaurantName { get; set; }
public string CategoryName { get; set; }
public string FourSquareID { get; set; }
}
public class rest_collection
{
public List<rest_all_data> rest_all_data { get; set; }
}
and here is the service:
public void AddRestaurantMultiple([FromBody] JObject rest_all)
{
string k = rest_all.ToString();
rest_collection result = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<rest_collection>(k);
}
and here is the json object:
"restaurants" : [{"RestaurantName":"a","CategoryName":"b","FourSquareID":"c"},{"RestaurantName":"d","CategoryName":"e","FourSquareID":"f"}]
the rest_all object always comes with data and the k string is also a success but the result variable is always null...
try it i have made few changes in your code
public class rest_collection
{
public IEnumerable<rest_all_data> rest_all_datas { get; set; }
}
public void AddRestaurantMultiple([FromBody] JObject rest_all)
{
string k = rest_all.ToString();
JavaScriptSerializer serializer = new JavaScriptSerializer();
rest_collection collection = serializer.Deserialize<rest_collection>(k);
}
try:
public void AddRestaurantMultiple([FromBody] string rest_all)
{
var obj = JsonConvert.DeserializeObject<rest_collection>(rest_all);
}
I have one xml file and I want to generate custom list from that xml using Linq.
here is my code. But I am not getting any records.Here is my code.
public class TemplateSettings {
public string DecimalSeparator { get; set; }
public string ThousandSeparator { get; set; }
public string DateSeparator { get; set; }
public string TimeSeparator { get; set; }
}
XML Here
<TemplateSetting>
<DecimalSeparator>1</DecimalSeparator>
<ThousandSeparator>2</ThousandSeparator>
<DateSeparator>3</DateSeparator>
<TimeSeparator>4</TimeSeparator>
<DateFormat>dd/MM/yyyy</DateFormat>
<ValueDelimiter>tr</ValueDelimiter>
<QuoteCharacter>r</QuoteCharacter>
<IsHeader>False</IsHeader>
</TemplateSetting>
And my code to get object from xml is
var a = (from x in objTemplateMasterEAL.TemplatSettingsXML.Elements("TemplateSetting")
select new TemplateSettings()
{
DateFormat = (string)x.Element("DateFormat"),
DecimalSeparator = (string)x.Element("DecimalSeparator"),
ThousandSeparator = (string)x.Element("ThousandSeparator"),
DateSeparator = (string)x.Element("DateSeparator"),
TimeSeparator = (string)x.Element("TimeSeparator"),
QuoteCharacter = (string)x.Element("QuoteCharacter"),
ValueDelimiter = (string)x.Element("ValueDelimiter"),
IsHeaderLine = (bool)x.Element("IsHeader")
}).ToList<TemplateSettings>();
Can any one suggest me what is wrong here ?
If your goal is just to deserialize the XML to object you can simply use this:
class Program
{
static void Main(string[] args)
{
using (StreamReader reader = new StreamReader("Sample.xml"))
{
var serializer = new XmlSerializer(typeof(TemplateSetting));
var templateSetting = (TemplateSetting)serializer.Deserialize(reader);
}
}
}
[XmlRoot]
public class TemplateSetting
{
public string DecimalSeparator { get; set; }
public string ThousandSeparator { get; set; }
public string DateSeparator { get; set; }
public string TimeSeparator { get; set; }
}
I make only on one change and its working fine for me.
<TemplateSettings>
<TemplateSetting>
<DecimalSeparator>1</DecimalSeparator>
<ThousandSeparator>2</ThousandSeparator>
<DateSeparator>3</DateSeparator>
<TimeSeparator>4</TimeSeparator>
<DateFormat>dd/MM/yyyy</DateFormat>
<ValueDelimiter>tr</ValueDelimiter>
<QuoteCharacter>r</QuoteCharacter>
<IsHeader>False</IsHeader>
</TemplateSetting>
</TemplateSettings>