I have a class MyItems in my namespace as
[DataContract]
public class MyItems {
[DataMember]
public int LineNum { get; set; }
[DataMember]
public string ItemCode { get; set; }
[DataMember]
public string Priority { get; set; }
[DataMember]
public string Contact { get; set; }
[DataMember]
public string Message { get; set; }
}
and on an XAML I have a button and in its action listener, I am trying to deserialize the JSON string that is coming from a form and trying to update a DataGrid.
In the first step Inside the action listener, I am trying..
List<MyItems> myItems= JSONHelper.DeserializeToMyItems<myItems>(result);
and result (of type string ) has
{"MyItems":[{"LineNum":"1","ItemCode":"A00001","Contact":"5","Priority":"1","Message":"IBM Infoprint 1312"}, {"LineNum":"2","ItemCode":"A00002","Contact":"5","Priority":"1","Message":"IBM Infoprint 1222"}, {"LineNum":"3","ItemCode":"A00003","Contact":"5","Priority":"1","Message":"IBM Infoprint 1226"}, {"LineNum":"4","ItemCode":"A00004","Contact":"5","Priority":"1","Message":"HP Color Laser Jet 5"}, {"LineNum":"5","ItemCode":"A00005","Contact":"5","Priority":"1","Message":"HP Color Laser Jet 4"}]}
The JSONHelper.DeserializeToMyItems code looks like,
public static List<MyItems> DeserializeToMyItems<MyItems>(string jsonString) { MyItems data = Activator.CreateInstance<MyItems>(); using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<MyItems>)); return (List<MyItems>)serializer.ReadObject(ms); } }
While running, I get an exception at the line serializer.ReadObject(ms)
Unable to cast object of type 'System.Object' to type 'System.Collections.Generic.List`1[ServiceTicket.MyItems]'.
I am not sure how to do a type cast for and I am handling a List of type MyItems. Can anyone help me on this please ?. would be highly appreciated as I am new on Silverlight.
thanks
Denny
Try following, it should resolve your problem.
public class JsonHelper
{
public static T Deserialize<T>(string json)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
}
and use the above method like following:
List<MyItems> myItems = JsonHelper.Deserialize<List<MyItems>>(result);
Hope this helps!
Related
I have the following class...
[JsonObject]
public class Response
{
[JsonProperty]
public RequestStatusCode StatusCode { get; set; }
[JsonProperty]
public String StatusMessage { get; set; }
[JsonProperty]
public Dictionary<String,String> response { get; set; }
[JsonProperty]
public DataSet dataResponse { get; set; }
public Response()
{
StatusMessage = String.Empty;
response = new Dictionary<string, string>();
dataResponse = new DataSet();
}
}
After serialization with JSON.NET using JsonConvert.SerializeObject(myObject) I get the following beautiful JSON string (just an example):
{"StatusCode":0,"StatusMessage":"Succeed.","response":{},"dataResponse":{"Table":[{"LabelID":355,"ProductID":1005,"InternalPN":"111INT","Description":"Produs2","WorkOrderSerialNumber":"0000000005","LabelNumber":1,"BarCode":"P000000000500001","Pallet":true,"LabelStatusID":1,"StatusName":"Printed","UserIDAddStatus":1004,"UserNameAddStatus":"test1","DataAddStatus":"2017-03-15T18:42:27.01","IsValidScan":false}]}}
Well, the problem comes when it's time to recreate the original object using
myObject =JsonConvert.DeserializeObject<Response>(json)
in the DataSet property dataResponse there is no data loaded. All the other properties are ok except this. There is no error, no nothing.
Is there any solution to recreate the original object using JSON.NET?
Thanks a lot!
Json libarary to convert data to json
this is my main method which return two list one with property list
List and another is List
public static Tuple<List<RoomDayBook>, List<string>> DayBookRowData(DateTime StartDate, DateTime EndDate, int SupplierId, bool wantSubRoom)
{
DataSet dsDayBook = FillDayBookData(StartDate, EndDate, SupplierId);
............................
............................
lstDayBook.Add(objDayBook);
}
return new Tuple<List<RoomDayBook>, List<string>>(lstDayBook, Guests);
}
In this RoomDayBook class in which i use JsonProperty which give jsonproperty name in json serilization in stand of property name
public class RoomDayBook
{
[JsonProperty(PropertyName = "RC")]
public string RoomCode { get; set; }
[JsonProperty(PropertyName = "RN")]
public string RoomName { get; set; }
[JsonProperty(PropertyName = "HS")]
public bool HasSubRoom { get; set; }
[JsonProperty(PropertyName = "RD")]
public List<RoomDetail> RoomDetails { get; set; }
[JsonProperty(PropertyName = "SRs", NullValueHandling = NullValueHandling.Ignore)]
public List<RoomDayBook> SubRooms { get; set; }
}
it's woking perfectly in normal aspx webmethods but not working in web api please help me find me reason behind it
I found problem in different version of Newton.json library different between class library and Web API Project that's it not convert it in proper format
I have this data class for storing data parsed from JSON formatted web data (using Json.NET library):
[Serializable()]
public class MovieData
{
public string FilePath { get; set; }
public string OrigName { get; set; }
[JsonProperty(PropertyName = "id")]
public int Id { get; set; }
[JsonProperty(PropertyName = "year")]
public int Year { get; set; }
[JsonProperty(PropertyName = "genres")]
public string[] Genres { get; set; }
}
The next class is for to be able serialize collection of MovieData objects:
[Serializable()]
[XmlRoot("MovieCollection")]
public class MovieCollection
{
[XmlArray("Movies")]
[XmlArrayItem("Movie", typeof(Movie))]
public List<Movie> movies = new List<MovieData>();
}
Finally, I need to bind such a collection of MovieData to DataGridView (or single MovieData object to DataGridViewRow), like:
dgvMovies.DataSource = movieCollection.movies;
Is it possible to bind it without hard-setting of DataGridViewColumn collection before? Native data types are not problem, problem is string[] Genres array, which I need to format it in DataGridView in some way, like:
"genres[0] / genres[0] / ... genres[n]"
At this moment, while simply setting DataSource to collectin, this array is ignored (is not displayed anyway).
In MovieData class, you can add the following property :
public string GenresAsString
{
get { return String.Join("/", Genres); }
set { Genres = value.Split('/'); }
}
You will surely have to improve the setter to make it more resilient (triming, removing empty genres) if you plan to let the user modify this value.
Else you can remove the setter.
Hi firends i'm getting error when i tried to Serialize JSON. I have a model and it have List property;
MyModel:
public virtual int Kod { get; set; }
public virtual string Ad { get; set; }
public virtual string TrafikKod { get; set; }
public virtual int TapuKod { get; set; }
public virtual bool AktifMi { get; set; }
[JsonIgnore]
public virtual IList<TapuIlceModel> IlceList { get; set; }
public TapuIlModel()
{
IlceList = new List<TapuIlceModel>();
}
MyApiController:
[Route("api/TapuZeminApi/GetZemins")]
[HttpPost]
public string GetZeminsFromZeminArg(object arg)
{
ZeminArg zemArg = SConvert.DeserializeJSON<ZeminArg>(arg.ToString());
List<TapuZeminModel> zeminList = TapuModule.GetZeminListFromArgs(zemArg);
string jsonResult = SConvert.SerializeJSON(zeminList);
return jsonResult;
Here is a picture about my reciving data error;
And this my inner exc.;
.{"Error getting value from 'ReadOnly' on 'NHibernate.Proxy.DefaultLazyInitializer'."}
.{"Proxy is detached (i.e, session is null). The read-only/modifiable setting is only accessible when the proxy is associated with an open session."}
What should i do? I need all data... Thanks
when i check again i found something like that:
Why is there 2 base??? And why name is different? Anyone know?
I geting same error when serilize SerializeJSON(object) , i have try JsonConvert.SerializeObject with JsonSerializerSettings and ContractResolver, it will work.
string jsonResult = JsonConvert.SerializeObject(object, new JsonSerializerSettings() {
ContractResolver = new NHibernateContractResolver()
});
I am trying to filter Kendo UI grid server side filter. The developer tools show this in query string
/Home/GetUsmMessage?{"filter":{"logic":"and","filters" [{"field":"MessageId","operator":"eq","value":1}]},"group":[]} GET 200 application/json
I created a object structure so that I read the structure to object
public ActionResult GetUsmMessage(FilterContainer filter)
{
//Code to read the filter container
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Object structure for filter container:
public class FilterContainer
{
public List<FilterDescription> filters { get; set; }
public string logic { get; set; }
}
public class FilterDescription
{
public string #operator { get; set; }
public string field { get; set; }
public string value { get; set; }
public List<FilterDescription> filters { get; set; }
public string logic { get; set; }
}
It still gives me a null object when I debug controller function. Please help
Got the answer...I forgot to add type of request as Http post ....
In case of WebApi controller, you could use [FromUri] attributes and GET verb:
public HttpResponseMessage Get(
[FromUri]IEnumerable<SortParameter> sort,
[FromUri]FilterContainer filter,
int take = 10, int skip = 0)