I have the below classes.
public class Source { public string ConfigData { get; set; } }
public class Configuration { public IEnumerable<IpAddress> IpAddresses { get; set; } }
public class IpAddress
{
public string Start { get; set; }
public string End { get; set; }
public bool IsValid { get; set; }
public Family IPFamily { get; set; }
}
First, I am getting the ConfigData as string from a source and deserializing it below:
var storedIPAddresses = JsonConvert.DeserializeObject<Configuration>( source.ConfigData).IpAddresses;
Next I am doing some checks, which essentially sets the values of IsValid and IPFamily.
if (storedIPAddresses.Any())
{
foreach (var ipDetail in storedIPAddresses)
{
if (!string.IsNullOrEmpty(ipDetail.StartIpAddress) && !string.IsNullOrEmpty(ipDetail.EndIpAddress))
{
if (bla == blabla)
{
ipDetail.IsValid = true;
ipDetail.IPFamily = IPAddressFamily.IPV4;
}
}
}
}
Lastly, I am supposed to return the souce object by chucking in the updated storedIPAddresses inside, which is where I need some guidance.
I am able to do in following way; but looking for any more elegant way?
var config = new Configuration();
config = JsonConvert.DeserializeObject<Configuration>(source.ConfigData);
config.IpAddresses = storedIPAddresses;
source.ConfigData = JsonConvert.SerializeObject(config);
return source;
Related
All - I've stumbled into a scenario that's causing me quite a bit of grief. I have a json structure (produced by gateio api) which on the face of it, looks super simple to deserialize into an object. the jsonTickerString looks like the below:
{
"method":"ticker.update",
"params":[
"BTC_USDT",
{
"period":86400,
"open":"46721.06",
"close":"48130.43",
"high":"48758.59",
"low":"46330.3",
"last":"48130.43",
"change":"2.95",
"quoteVolume":"2246.8399550054",
"baseVolume":"106183751.468785134437"
}
],
"id":null
}
However, this is proving to be deceptively funky when trying to push it into an object model. I derived the object model below and thought we were all set to go:
public partial class GateIoTicker
{
[JsonProperty("method")]
public string Method { get; set; }
[JsonProperty("params")]
public List<ParamElement> Params { get; set; }
[JsonProperty("id")]
public object Id { get; set; }
}
public class ParamClass
{
[JsonProperty("period")]
public long Period { get; set; }
[JsonProperty("open")]
public string Open { get; set; }
[JsonProperty("close")]
public string Close { get; set; }
[JsonProperty("high")]
public string High { get; set; }
[JsonProperty("low")]
public string Low { get; set; }
[JsonProperty("last")]
public string Last { get; set; }
[JsonProperty("change")]
public string Change { get; set; }
[JsonProperty("quoteVolume")]
public string QuoteVolume { get; set; }
[JsonProperty("baseVolume")]
public string BaseVolume { get; set; }
}
public partial struct ParamElement
{
public string coinName;
public ParamClass quoteParams;
public static implicit operator ParamElement(ParamClass quoteparams)
{
return new ParamElement { quoteParams = quoteparams };
}
public static implicit operator ParamElement(string coinname)
{
return new ParamElement { coinName = coinname };
}
}
I then set about populating the object using the standard Json.Net approach:
var gateIoTicker = JsonConvert.DeserializeObject<GateIoTicker>(jsonTickerString);
However, although this correctly deserializes the string element in the "params" object, no amount of coersion will bring about a deserialization of the ParamClass object.
Am I missing something very obvious here?? I've spent an inordinate amount of time trying to figure this out and think it's now time to solicit some superior brain power.
Hope this scans as expected...
[Edit] - further to Serge's suggestion, i took his code and added it as a method on my GatIoTicker object. Would have preferred an option that desrializes using attributes, but this works perfectly. Refactored code looks like:
public partial class GateIoTicker
{
[JsonProperty("method")]
public string Method { get; set; }
[JsonProperty("params")]
public List<ParamElement> Params { get; set; }
[JsonProperty("id")]
public object Id { get; set; }
public GateIoTicker FromJson(string json)
{
var jsonObject = JObject.Parse(json);
var pars = jsonObject["params"] as JArray;
var paramElement = new ParamElement();
foreach (var jObject in pars)
{
if (jObject.GetType().Name.ToString() == "JValue") paramElement.ParamName = ((JValue)jObject).ToString();
else
{
paramElement.ParamBody = jObject.ToObject<ParamClass>();
}
}
GateIoTicker gateIoTicker = new GateIoTicker { Params = new List<ParamElement>() };
gateIoTicker.Id = (string)jsonObject["Id"];
gateIoTicker.Method = (string)jsonObject["method"];
gateIoTicker.Params.Add(paramElement);
return gateIoTicker;
}
}
public partial class ParamElement
{
public string ParamName { get; set; }
public ParamClass ParamBody {get; set;}
}
thanks again for the suggestions and nudges. seasons greetings
Try this, it was tested in Visual studio
var jsonObject = JObject.Parse(json);
var pars = jsonObject["params"] as JArray;
var paramElement = new ParamElement();
foreach (var jObject in pars)
{
if (jObject.GetType().Name.ToString() == "JValue") paramElement.ParamName = ((JValue)jObject).ToString();
else
{
paramElement.ParamBody=jObject.ToObject<ParamClass>();
}
}
GateIoTicker gateIoTicker = new GateIoTicker {Params= new List<ParamElement>()};
gateIoTicker.Id= (string) jsonObject["Id"];
gateIoTicker.Method= (string) jsonObject["method"];
gateIoTicker.Params.Add(paramElement);
ParamElement class
public partial class ParamElement
{
public string ParamName { get; set; }
public ParamClass ParamBody {get; set;}
}
I have a string stream returning JSON data from and API that looks like this:
"{\"Recs\":
[
{\"EID\":\"F67_24_6\",\"ReturnPeriod\":\"1\",\"GageStation\":\"NA\"},
{\"EID\":\"T67_24_6\",\"ReturnPeriod\":\"2.37\",\"GageStation\":\"Magueyes Island\"},
{\"EID\":\"R67_24_6\",\"ReturnPeriod\":\"1\",\"GageStation\":\"50147800\"}
]}"
I am trying to deserialize it to return this:
{"Recs":[
{"EID":"F67_24_6","ReturnPeriod":"1","GageStation":"NA"},
{"EID":"T67_24_6","ReturnPeriod":"2.37","GageStation":"Magueyes Island"},
{"EID":"R67_24_6","ReturnPeriod":"1","GageStation":"50147800"}
]}
I am using these public classes to structure the return:
public class New_Events_Dataset
{
public string EID { get; set; }
public string ReturnPeriod { get; set; }
public string GageStation { get; set; }
}
public class NewRootObject
{
public List<New_Events_Dataset> Reqs { get; set; }
}
When I try to apply this later, I basically get a return of {"Reqs":null}. What am I doing wrong here?
var jsonResponse = JsonConvert.DeserializeObject<NewRootObject>(strresult);
string json = new JavaScriptSerializer().Serialize(jsonResponse);
return json;
I think Reqs should be Recs:
public class NewRootObject
{
public List<New_Events_Dataset> Reqs { get; set; }
}
try:
public class NewRootObject
{
public List<New_Events_Dataset> Recs { get; set; }
}
Rename Reqs to Recs and create default constructor of class and instantiate Recs list
public class NewRootObject
{
List<New_Events_Dataset> Recs { get; set; }
public NewRootObject()
{
Recs = new List<New_Events_Dataset>();
}
}
I have developed my first API controlled in MVC4 and through the scaffolding I have got it to automatically output a list of items:
// GET api/ItemList
public IEnumerable<ItemOption> GetItemOptions()
{
var itemoptions = db.ItemOptions.Include(i => i.Item);
return itemoptions.AsEnumerable();
}
This shows all the item properties from my model:
public class ItemOption
{
public int ItemOptionId { get; set; }
public bool Active { get; set; }
public string Name { get; set; }
public string test1 { get; set; }
public double PriceNet { get; set; }
}
How can I specify specific fields I wish to be returned? For example, I just want the ItemOptionId, Active and Name to be returned.
I have tried adding additional includes, but this seems to be at an object level.
Try creating a new type to represent the properties you'd like to return:
public class ItemOptionResult
{
public int ItemOptionId { get; set; }
public bool Active { get; set; }
public string Name { get; set; }
}
And then projecting your ItemOption collection, like this:
// GET api/ItemList
public IEnumerable<ItemOptionResult> GetItemOptions()
{`enter code here`
var itemoptions =
db.ItemOptions
.Select(i =>
new ItemOptionResult
{
ItemOptionId = i.ItemOptionId,
Active = i.Active,
Name = i.Name
});
return itemoptions.AsEnumerable();
}
Try this :
var itemoptions = db.ItemOptions.Select(io => new ItemOption()
{
ItemOptionId = io.ItemOptionId,
Active = io.Active ,
Name = io.Name
}
return itemoptions.AsEnumerable();
I build a rest service which output are json. I using Newtonsoft.Json.
This is my class.
public class DownloadPDA
{
public List<FRUTE> lsRute { get; set; }
public List<FCUSTMST> lsCustomer { get; set; }
public List<FMASTER> lsMaster { get; set; }
public List<FNOTEC> lsNotec { get; set; }
public List<FINFO> lsInfo { get; set; }
public List<FBRAND> lsBrand { get; set; }
public List<FKPL> lsKpl { get; set; }
}
but when I test my rest service my result are:
{"downloadDataResult":"{"lsBrand":[{}],"lsCustomer":[{},{},{}],"lsInfo":[],"lsKpl":null,"lsMaster":[{},{},{},{},{}],"lsNotec":[],"lsRute":[{},{},{}]}"}
it not show the data in list. I know something is wrong. Can anybody help?
This one of my collection class
public class FRUTE
{
private String norute;
private String custno;
private String flag;
private String st_visit;
private float amount;
private int jmlvisit;
public FRUTE() { }
public void getData(DCTRTDTO dto) {
this.norute = dto.NOROUT;
this.custno = dto.NOCUST;
this.flag = dto.FLAG;
this.st_visit = "not yet";
this.amount = 10;
this.jmlvisit = 1;
}
public static List<FRUTE> getList(List<DCTRTDTO> lsRute)
{
List<FRUTE> ls = new List<FRUTE>();
FRUTE info = new FRUTE();
foreach (DCTRTDTO dto in lsRute)
{
info.getData(dto);
ls.Add(info);
}
return ls;
}
}
Your FRUTE class doesn't have public properties that are required for Json serialization.
Encapsulate you private fields and all will work as expected.
public class FRUTE
{
private String norute;
private String custno;
public string Norute
{
get { return norute; }
set { norute = value; }
}
public string Custno
{
get { return custno; }
set { custno = value; }
}
//...
}
I try to deserialization a JSON like the following(Numbers like 93817 and 935812 are dynamically generated from a server. Can't be hard coded.):
{ "status":"1",
"list":{
"93817":{ "item_id":"93817",
"url":"http://url.com",
"title":"Page Title",
"time_updated":"1245626956",
"time_added":"1245626956",
"tags":"comma,seperated,list",
"state":"0"
},
"935812":{ "item_id":"935812",
"url":"http://google.com",
"title":"Google",
"time_updated":"1245626956",
"time_added":"1245626956",
"tags":"comma,seperated,list",
"state":"1"
} }}
Here is the code for deserialization:
responseGetList = e.Result.ToString(); //responseGetList is the JSON string
MemoryStream ms = new MemoryStream( Encoding.Unicode.GetBytes(responseGetList));
DataContractJsonSerializer serializer =
new DataContractJsonSerializer( typeof(List<ResponseItem>) );
ResponseItem li = (ResponseItem)serializer.ReadObject(ms);
And the following is the ResponseItem class:
namespace whatever
{
[DataContract]
public class ResponseItem
{
[DataMember(Name = "status")]
string status;
public string Status
{
get { return status; }
set { status = value; }
}
[DataMember(Name = "list")]
List<ListItem> list;
private List<ListItem> List
{
get { return list; }
set { list = value; }
}
}
public class ListItem
{
[DataMember]
List<Article> listArticle;
public List<Article> ListArticle
{
get { return listArticle; }
set { listArticle = value; }
}
}
}
public class Article
{
[DataMember(Name = "item_id")]
string item_id;
public string Item_id
{
get { return item_id; }
set { item_id = value; }
}
[DataMember(Name = "url")]
string url;
public string Url
{
get { return url; }
set { url = value; }
}
[DataMember(Name = "title")]
string title;
public string Title
{
get { return title; }
set { title = value; }
}
[DataMember(Name = "time_updated")]
string time_updated;
public string Time_updated
{
get { return time_updated; }
set { time_updated = value; }
}
[DataMember(Name = "time_added")]
string time_added;
public string Time_added
{
get { return time_added; }
set { time_added = value; }
}
[DataMember(Name = "tags")]
string tags;
public string Tags
{
get { return tags; }
set { tags = value; }
}
[DataMember(Name = "state")]
string state;
public string State
{
get { return state; }
set { state = value; }
}
}
I get InvalidCastException on 1ataContractJsonSerializer serializer =
new DataContractJsonSerializer( typeof(List<ResponseItem>) );, I think it is a JSON-Object mapping problem. Can any one help me?
Try using NewtonSoft's LINQ to Json, it's a way cleaner method to de/serialize json strings
ClassName class= new ClassName();
objectname = JsonConvert.DeserializeObject<ClassName>(responseGetList);
Use Json2C# to create the ClassName you need to have to be able to deserialize straight into an object.
You can use object.__ to call upon any of the results: example with your code:
object.list.(93817(you will have to cast this with a JsonProperty, because c# doesn't allow methods with solely numbers)).item_id = 93817
cleaner : object.list.thenameyougavethemethod.item_id
Good luck, if you have more questions, just add comments
EDIT : I parsed the json string and added JsonProperties to your specific Json String;
Just download the NewtonSoft .dll & don't forget to add a reference to your project ...
public class id93817
{
public string item_id { get; set; }
public string url { get; set; }
public string title { get; set; }
public string time_updated { get; set; }
public string time_added { get; set; }
public string tags { get; set; }
public string state { get; set; }
}
public class id935812
{
public string item_id { get; set; }
public string url { get; set; }
public string title { get; set; }
public string time_updated { get; set; }
public string time_added { get; set; }
public string tags { get; set; }
public string state { get; set; }
}
public class List
{
[JsonProperty("93817")]
public id93817 { get; set; }
[JsonProperty("935812")]
public id935812 { get; set; }
}
public class RootObject
{
public string status { get; set; }
public List list { get; set; }
}
Try switching to Json.NET for deserializing the object. It is less error prone and fragile (and yes, it's open source and works on the phone)>
The first item in the lists are incorrect. Your JSON shows "93817" and "935812" but those are not properties on your items. The first part of your JSON must be a property name. You're doing it right for "list" because it corresponds to the List property of ResponseItem. Change those numbers to "listArticle". I also second Shawn Wildermuth's suggestion for JSON.Net.
The JSON that is generated on the server should be serialized the same way that it is deserialized (ie: use the same framework to (de)serialize). If you are generating the JSON by hand, don't. You will have more problems than you need or want.
If you serialize the object, you should have the following:
{ "status":"1",
"list":{
"listArticle":{
"item_id":"93817",
"url":"http://url.com",
"title":"Page Title",
"time_updated":"1245626956",
"time_added":"1245626956",
"tags":"comma,seperated,list",
"state":"0"
},
"listArticle":{
"item_id":"935812",
"url":"http://google.com",
"title":"Google",
"time_updated":"1245626956",
"time_added":"1245626956",
"tags":"comma,seperated,list",
"state":"1"
}
}
}
Issue resolved by reading the source code of RIL# (http://rilsharp.codeplex.com/).
The problem is mainly mapping issue. Using Dictionary is the key resolution:
[DataContract]
public class ResponseItem
{
[DataMember(Name = "status")]
public ListStatus Status { get; set; }
[DataMember(Name = "since")]
public double Since { get; set; }
[DataMember(Name = "list")]
public Dictionary<string, RilListItem> items { get; set; }
public DateTime SinceDate
{
get
{
return UnixTime.ToDateTime(Since);
}
}
Then using Json.net to deserialize the JSON:
ResponseItem ri = new ResponseItem();
ri = JsonConvert.DeserializeObject<ResponseItem>(responseGetList);