I have a POCO like this:
public class Process
{
public Process() { }
[DataMember(Name = "lang_code")]
public string LCode { get; set; }
[DataMember(Name = "data_currency")]
public string Currency { get; set; }
[DataMember(Name = "country_code")]
public string CCode { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
Now when I serialize my POCO I get json back like this which has field name:
{"LCode":"en-US","Currency":"USD","CCode":"IN"}
Is there any way to get it the way DataMember fields are after serializing POCO. Something like below:
{"lang_code":"en-US","data_currency":"USD","country_code":"IN"}
Below is the code we have:
ProcessStr = ExtractHeader(headers, PROCESS_HEADER);
Console.WriteLine(ProcessStr);
if (!string.IsNullOrWhiteSpace(ProcessStr))
{
Process = DeserializeJson<Process>(ProcessStr);
if (Process != null && !string.IsNullOrWhiteSpace(Process.Gold))
{
Process.Gold = HttpUtility.HtmlEncode(Process.Gold);
}
ProcessStr = Process.ToString();
Console.WriteLine(ProcessStr);
}
private T DeserializeJson<T>(string str) where T : new()
{
try
{
return Utf8Json.JsonSerializer.Deserialize<T>(str);
}
catch (Exception e)
{
return new T();
}
}
It looks like you are using two different packages, Newtonsoft.Json to serialize and Utf8Json to deserialize. They use different annotations. You can get it to work, but it might be simpler to choose one or the other.
Newtonsoft.Json uses the JsonProperty attribute whereas Utf8Json uses the DataMember one.
using System;
using System.Diagnostics;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Utf8Json;
namespace JSONPropertyTest
{
public class Process
{
public Process() { }
[JsonProperty("lang_code")]
[DataMember(Name = "lang_code")]
public string LCode { get; set; }
[JsonProperty("data_currency")]
[DataMember(Name = "data_currency")]
public string Currency { get; set; }
[JsonProperty("country_code")]
[DataMember(Name = "country_code")]
public string CCode { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
class Program
{
static private T DeserializeJson<T>(string str) where T : new()
{
try
{
return Utf8Json.JsonSerializer.Deserialize<T>(str);
}
catch (Exception e)
{
return new T();
}
}
static void Main(string[] args)
{
var test = new Process { LCode = "en-US",Currency = "USD", CCode = "IN" };
var json = test.ToString();
Console.WriteLine($"serialized={test}");
var deserialized = DeserializeJson<Process>(json);
Debug.Assert(test.CCode == deserialized.CCode);
Debug.Assert(test.LCode == deserialized.LCode);
Debug.Assert(test.Currency == deserialized.Currency);
Console.WriteLine($"deserialized={deserialized}");
}
}
}
To just use Utf8Json you need to update your ToString method, which is the only one in the code you've shown that relies on Newtonsoft.Json. That would look like this:
public class Process
{
public Process() { }
[DataMember(Name = "lang_code")]
public string LCode { get; set; }
[DataMember(Name = "data_currency")]
public string Currency { get; set; }
[DataMember(Name = "country_code")]
public string CCode { get; set; }
public override string ToString()
{
return Utf8Json.JsonSerializer.ToJsonString(this);
}
}
Related
I want to call a method for my WPF-App with subtype objects of my Piece class. My problem is that the subtype objects have more properties than e.g the the Text objects.
Do you know a way to cope with this better than I do in my FillForm example?
namespace Namespace
{
public abstract class Piece
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
}
public class Text : Piece
{
}
public class Image: Piece{
public string filePath { get; set; }
public string fileformat { get; set; }
}
public class Video : Image
{
}
}
}
Example method:
public void FillForm(Piece currentPiece)
{
pieceIdTextBox.Text = currentPiece.id.ToString();
pieceNameTextBox.Text = currentPiece.title;
pieceDescriptionTextBox.Text = currentPiece.description;
if (!currentPiece.GetType().ToString().Equals("Namespace.Text"))
{
pieceFileSelectURLTextBlock.Text = (currentPiece as Namespace.Image).filePath;
SetPreviews((currentPiece as Namespace.Image).filePath);
}
}
Thanks!
Why not just change the method to the following with more type-safety
public void FillForm(Piece currentPiece)
{
pieceIdTextBox.Text = currentPiece.id.ToString();
pieceNameTextBox.Text = currentPiece.title;
pieceDescriptionTextBox.Text = currentPiece.description;
if (currentPiece as Namespace.Image imagePiece)
{
pieceFileSelectURLTextBlock.Text = imagePiece.filePath;
SetPreviews(imagePiece.filePath);
}
}
Do a safecast:
public void FillForm(Piece currentPiece)
{
pieceIdTextBox.Text = currentPiece.id.ToString();
pieceNameTextBox.Text = currentPiece.title;
pieceDescriptionTextBox.Text = currentPiece.description;
var imagePiece = currentPiece as Image;
if(imagePiece != null)
pieceFileSelectURLTextBlock.Text = imagePiece .filePath;
SetPreviews(imagePiece .filePath);
}
}
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; }
}
I'm trying to deserialize xml retrieved from a web service call
using (var client = new WebClient())
{
client.UseDefaultCredentials = true;
var content = client.DownloadString("call to service");
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<NewCourseApply.Models.Education>));
using (TextReader textReader = new StringReader(content))
{
var e = (List<NewCourseApply.Models.Education>)serializer.Deserialize(textReader);
}
}
The xml returned from the service is:
<ArrayOfEducation xmlns="http://schemas.datacontract.org/2004/07/CovUni.Domain.Admissions" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Education><_auditList xmlns="http://schemas.datacontract.org/2004/07/CovUni.Common.Base" xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/><_apCode>670104552</_apCode><_attendanceType>FT</_attendanceType><_educationId>1</_educationId><_establishmentDetails>test school</_establishmentDetails><_fromDate>2016-11-01T00:00:00</_fromDate><_toDate>2016-11-22T00:00:00</_toDate><_ucasSchoolCode/></Education></ArrayOfEducation>
My client side object is:
[Serializable]
public class Education
{
protected int _apCode;
protected int _educationId;
protected string _establishmentDetails;
protected string _ucasSchoolCode;
protected DateTime? _fromDate;
protected DateTime? _toDate;
protected string _attendanceType;
protected string _auditList;
public int ApCode
{ get { return _apCode;}
set { _apCode = value;} }
public int EducationId
{ get { return _educationId;}
set { _educationId = value;} }
public string EstablishmentDetails
{ get { return _establishmentDetails;}
set { _establishmentDetails = value;} }
public string UcasSchoolCode
{ get { return _ucasSchoolCode;}
set { _ucasSchoolCode = value;} }
public DateTime? FromDate
{ get { return _fromDate;}
set { _fromDate = value;} }
public DateTime? ToDate
{ get { return _toDate;}
set { _toDate = value;} }
public string AttendanceType
{ get { return _attendanceType;}
set { _attendanceType = value;} }
public string AuditList
{ get { return _auditList;}
set { _auditList = value;} }
}
The error I am getting is:
There is an error in XML document (1, 2).
<ArrayOfEducation xmlns='http://schemas.datacontract.org/2004/07/CovUni.Domain.Admissions'> was not expected.
Also if I call a web service call and get the singular Education response i.e.:
<Education xmlns="http://schemas.datacontract.org/2004/07/CovUni.Domain.Admissions" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><_auditList xmlns="http://schemas.datacontract.org/2004/07/CovUni.Common.Base" xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/><_apCode>670104552</_apCode><_attendanceType>FT</_attendanceType><_educationId>1</_educationId><_establishmentDetails>test school</_establishmentDetails><_fromDate>2016-11-01T00:00:00</_fromDate><_toDate>2016-11-22T00:00:00</_toDate><_ucasSchoolCode/></Education>
Surely I just need one Simple Education class on the client side that can deserialise from the 2 examples of xml i have provided i.e. array and non array
Can some of you kind souls let me know where i'm going wrong or if there's a better way of doing this?
Many Thanks
Change the Class to
[XmlRoot("ArrayOfEducation", Namespace = "http://schemas.datacontract.org/2004/07/CovUni.Domain.Admissions")]
public class ArrayOfEducation
{
[XmlElement("Education")]
public List<ContainerEducation> education { get; set; }
}
public class ContainerEducation
{
[XmlElement(ElementName = "_apCode")]
public int _apCode { get; set; }
[XmlElement(ElementName = "_educationId")]
public int _educationId { get; set; }
[XmlElement(ElementName = "_establishmentDetails")]
public string _establishmentDetails { get; set; }
[XmlElement(ElementName = "_ucasSchoolCode")]
public string _ucasSchoolCode { get; set; }
[XmlElement(ElementName = "_fromDate")]
public DateTime? _fromDate { get; set; }
[XmlElement(ElementName = "_toDate")]
public DateTime? _toDate { get; set; }
[XmlElement(ElementName = "_attendanceType")]
public string _attendanceType { get; set; }
[XmlElement(ElementName = "_auditList", Namespace = "http://schemas.datacontract.org/2004/07/CovUni.Common.Base")]
public string _auditList { get; set; }
}
And Deserialize below way. Now, when I run the code to deserialize your XML, I do get the objects filled nicely.
XmlSerializer mySerializer = new XmlSerializer(typeof(ArrayOfEducation));
using (TextReader textReader = new StringReader(content))
{
ArrayOfEducation arrEdu = (ArrayOfEducation)mySerializer.Deserialize(textReader);
}
Update as per your comment:
If you are sure that web service is going to send single Education then you need to change the class to
[XmlRoot("ArrayOfEducation", Namespace = "http://schemas.datacontract.org/2004/07/CovUni.Domain.Admissions")]
public class ArrayOfEducation
{
[XmlElement("Education")]
public ContainerEducation education { get; set; }
}
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 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);
}