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>();
}
}
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;}
}
anyone know how to insert this json array into mongodb using insertmany() and C# ??
i cant find any good source for this problem
MongoCollectionBase.InsertMany expects an IEnumerable<TDocument>.
So you need to deserialize your data json element to TDocument[], (Datum) and then pass that array to InsertMany.
Based on the below json, which is different from your screenshot
{
"data": [
{
"pulsa_code": "alfamart100",
"pulsa_op": "Alfamart Voucher",
"pulsa_nominal": "Voucher Alfamart Rp 100.000",
"pulsa_price": 100000,
"pulsa_type": "voucher",
"masaaktif": "0",
"status": "active"
}
]
}
This should work
//...
public class Datum
{
public string pulsa_code { get; set; }
public string pulsa_op { get; set; }
public string pulsa_nominal { get; set; }
public double pulsa_price { get; set; }
public string pulsa_type { get; set; }
public string masaaktif { get; set; }
public string status { get; set; }
public double harga { get; set; }
}
public class PriceListPrepaidModel
{
public List<Datum> data { get; set; }
}
public class PriceList : BaseDatabase
{
//NOTE: The strongly typed IMongoCollection<T> must be the same type as the entities passed to InsertMany
private IMongoCollection<Datum> _pricelistCollection;
//private IMongoCollection<PriceListPrepaidModel> _pricelistCollection;
public PriceList(IServiceProvider serviceProvider)
{
_pricelistCollection = DB.GetCollection<PriceListPrepaidModel>("price_prepaid");
}
public ResponseModel<string> PriceListPrepaidTest(PriceListPrepaidRequest request)
{
var entityResult = new ResponseModel<string>();
try
{
Console.WriteLine(response.Content);
//Desirialize to your model class, not JObject
var model = JsonConvert.DeserializeObject<PriceListPrepaidModel>(message.AsString);
foreach (var item in model.data)
{
item.pulsa_price = (int)item.pulsa_price + 200;
}
//Insert the array of `Datum`
_pricelistCollection.InsertMany(model.data);
entityResult.Value = JsonConvert.SerializeObject(model.data);
entityResult.Status = true;
}
catch (Exception ex)
{
entityResult.Messages.Add(new ResponseMessageModel()
{
Type = ResponseMessageModel.MessageType.ERROR,
Title = "Error",
Message = ex.Message
});
}
return entityResult;
}
}
Im having with the content. it is auto increment.
the result is static but the content is dynamic.
I'm using a hardcoded array in catching the return string from the web. Can anyone json decoder in converting the returned string to c# object
This is the returned string from web:
{
"result":{
"count":"3"
},
"content_1":{
"message_id":"23",
"originator":"09973206870",
"message":"Hello",
"timestamp":"2016-09-14 13:59:47"
},
"content_2":{
"message_id":"24",
"originator":"09973206870",
"message":"Test again.",
"timestamp":"2016-09-14 14:49:14"
},
"content_3":{
"message_id":"25",
"originator":"09973206870",
"message":"Another message",
"timestamp":"2016-09-14 14:49:20"
}
}
On site json2csharp.com you can generate classes for JSON data.
Generated classes needs some improvements and can look like:
public class Result
{
public string count { get; set; }
}
public class Content
{
public string message_id { get; set; }
public string originator { get; set; }
public string message { get; set; }
public string timestamp { get; set; }
}
public class RootObject
{
public Result result { get; set; }
public Content content_1 { get; set; }
public Content content_2 { get; set; }
public Content content_3 { get; set; }
}
And using JSON.NET you can deserialize it:
public class Program
{
static public void Main()
{
string json = "{ \"result\":{ \"count\":\"3\" }, \"content_1\":{ \"message_id\":\"23\", \"originator\":\"09973206870\", \"message\":\"Hello\", \"timestamp\":\"2016-09-14 13:59:47\" }, \"content_2\":{ \"message_id\":\"24\", \"originator\":\"09973206870\", \"message\":\"Test again.\", \"timestamp\":\"2016-09-14 14:49:14\" }, \"content_3\":{ \"message_id\":\"25\", \"originator\":\"09973206870\", \"message\":\"Another message\", \"timestamp\":\"2016-09-14 14:49:20\" } }";
RootObject ro = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(ro.content_1.message_id);
Console.WriteLine(ro.content_2.message_id);
}
}
How can I deserialize the following JSON string to a datatable in c#
{
"m_MaxCapacity":2147483647,
"Capacity":1888,
"m_StringValue":"<table border=3><tr><th>Master ID</th><th>Tag ID</th><th>Plant ID</th><th>Machine Name</th><th>Sap ID</th><th>Log</th></tr><tr><td>2296</td><td>567</td><td>567</td><td>hjhnh</td><td>567</td><td>17-09-2016 15:03:04</td></tr><tr><td>2297</td><td>55555</td><td>567</td><td>hjhnh</td><td>567</td><td>17-09-2016 15:04:27</td></tr><tr><td>2298</td><td>55555</td><td>567</td><td>hjhnh</td><td>0000</td><td>17-09-2016 15:04:53</td></tr><tr><td>2299</td><td>55555</td><td>567</td><td>hjhnh</td><td>0000</td><td>17-09-2016 15:05:11</td></tr><tr><td>2300</td><td>6678</td><td>6754</td><td>nnn</td><td>789</td><td>17-09-2016 15:20:51</td></tr><tr><td>2301</td><td>6678</td><td>6754</td><td>AF</td><td>789</td><td>17-09-2016 15:23:57</td></tr><tr><td>2302</td><td>6678</td><td>6754</td><td>ttttttt</td><td>789</td><td>17-09-2016 15:33:22</td></tr><tr><td>2303</td><td>6678</td><td>6754</td><td>ttttttt</td><td>789</td><td>17-09-2016 15:43:10</td></tr><tr><td>2304</td><td>6678</td><td>6754</td><td>ttttttt</td><td>789</td><td>17-09-2016 15:43:23</td></tr><tr><td>2305</td><td>6678</td><td>6754</td><td>ttttttt</td><td>789</td><td>17-09-2016 15:43:50</td></tr><tr><td>2306</td><td>6678</td><td>6754</td><td>lmno</td><td>789</td><td>17-09-2016 15:49:25</td></tr><tr><td>2307</td><td>6678</td><td>6754</td><td>ttttttt</td><td>789</td><td>22-09-2016 11:23:16</td></tr><tr><td>2308</td><td>6678</td><td>6754</td><td>ttttttt</td><td>789</td><td>22-09-2016 11:40:07</td></tr><tr><td>2309</td><td>6678</td><td>6754</td><td>ccccc</td><td>789</td><td>22-09-2016 11:40:18</td></tr><tr><td>2310</td><td>6678</td><td>6754</td><td>ttttttt</td><td>789</td><td>22-09-2016 11:45:53</td></tr><tr><td>2311</td><td>6678</td><td>6754</td><td>ttttttt</td><td>789</td><td>22-09-2016 12:00:48</td></tr><tr><td>2312</td><td>6678</td><td>6754</td><td>mmmmmmmmmm</td><td>789</td><td>22-09-2016 12:00:52</td></tr></table>",
"m_currentThread":0
}
Any ideas welcome.
First you have to add package Newtonsoft.Json to your project.Next create class with object. You can use http://json2csharp.com/ it's very helpfull tool. Finally you have to Deserialize yours json. Try use this sample.
public class RootObject
{
public long m_MaxCapacity { get; set; }
public int Capacity { get; set; }
public string m_StringValue { get; set; }
public int m_currentThread { get; set; }
}
string json= {"m_MaxCapacity":2147483647,"Capacity":1888,"m_StringValue":"Master IDTag IDPlant IDMachine NameSap IDLog2296567567hjhnh56717-09-2016 15:03:04229755555567hjhnh56717-09-2016 15:04:27229855555567hjhnh000017-09-2016 15:04:53229955555567hjhnh000017-09-2016 15:05:11230066786754nnn78917-09-2016 15:20:51230166786754AF78917-09-2016 15:23:57230266786754ttttttt78917-09-2016 15:33:22230366786754ttttttt78917-09-2016 15:43:10230466786754ttttttt78917-09-2016 15:43:23230566786754ttttttt78917-09-2016 15:43:50230666786754lmno78917-09-2016 15:49:25230766786754ttttttt78922-09-2016 11:23:16230866786754ttttttt78922-09-2016 11:40:07230966786754ccccc78922-09-2016 11:40:18231066786754ttttttt78922-09-2016 11:45:53231166786754ttttttt78922-09-2016 12:00:48231266786754mmmmmmmmmm78922-09-2016 12:00:52","m_currentThread":0}
List<RootObject> list = new List<RootObject>();
list= JsonConvert.DeserializeObject<List<RootObject>>(json);
you can use: http://json2csharp.com/
there you get the class:
public class RootObject
{
public long m_MaxCapacity { get; set; }
public int Capacity { get; set; }
public string m_StringValue { get; set; }
public int m_currentThread { get; set; }
}
then you can add it to your context.
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);