C# JSON data serialized and binded to DataGridView - json

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.

Related

.net Web API Json Property attribute not working when serilize using JsonConvert.serilizeObject

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

Issue with MVC 3 model binder for propery which is a list of inherited objects

The issue is very similar to this post
How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?
However instead of trying to serialize a string manually we are attempting to use the model binding in MVC 3. So here is the scenario
[DataContract]
public class Company
{
[DataMember]
public List<Person> Employees { get; set; }
}
[DataContract]
public class Person
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
}
[DataContract]
[KnownType(typeof(Person))]
public class Employee : Person
{
[DataMember]
public string Department { get; set; }
[DataMember]
public string JobTitle { get; set; }
}
[DataContract]
[KnownType(typeof(Person))]
public class Artist : Person
{
[DataMember]
public string Skill { get; set; }
}
public JsonResult PopulateCompany()
{
Company model = new Company();
model.Employees = new List<Person>
{
new Employee(),
new Employee(),
new Artist(),
};
return Json(model, JsonRequestBehavior.AllowGet);
// in the View the model is correctly deserialized. E.g. we can see the properties from Artist
}
public ActionResult PopulateCompany(Company model)
{
// the returned model is also being populated except the Person object is being added to the Employees and we can no longer access the properties of Artist.
return View(model);
}
Thank you.
The model binding process involve first initializing the model. In your case it initializes an instance of Company with a property List<Person> Employees. Based on the values that are posted back, if a key/value pair is found that matches a Person (e.g. Persons[0].FirstName: "Ian") then a new instance of Person is initialized and its properties are set and added to the collection.
The DefaultModelBinder has no way of knowing that you want to initialize a different concrete type.
The easy solution is to use a view model containing collection properties of each type (e.g. public List<Employees> Employees { get; set; }; public List<Artist> Artists { get; set; }; etc).
The alternative (difficult) solution is to create a custom ModelBinder that will generate concrete types based on values in the model. This article (the section on Abstract Model Binder) is a good start for learning how to create a custom ModelBinder

How to omit Get only properties in servicestack json serializer?

I have an object which I am de-serializing using ToJson<>() method from ServiceStack.Text namespace.
How to omit all the GET only propeties during serialization? Is there any attribute like [Ignore] or something that I can decorate my properties with, so that they can be omitted?
Thanks
ServiceStack's Text serializers follows .NET's DataContract serializer behavior, which means you can ignore data members by using the opt-out [IgnoreDataMember] attribute
public class Poco
{
public int Id { get; set; }
public string Name { get; set; }
[IgnoreDataMember]
public string IsIgnored { get; set; }
}
An opt-in alternative is to decorate every property you want serialized with [DataMember]. The remaining properties aren't serialized, e.g:
[DataContract]
public class Poco
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
public string IsIgnored { get; set; }
}
Finally there's also a non-intrusive option that doesn't require attributes, e.g:
JsConfig<Poco>.ExcludePropertyNames = new [] { "IsIgnored" };
Dynamically specifying properties that should be serialized
ServiceStack's Serializers also supports dynamically controlling serialization by providing conventionally named ShouldSerialize({PropertyName}) methods to indicate whether a property should be serialized or not, e.g:
public class Poco
{
public int Id { get; set; }
public string Name { get; set; }
public string IsIgnored { get; set; }
public bool? ShouldSerialize(string fieldName)
{
return fieldName == "IsIgnored";
}
}
More examples in ConditionalSerializationTests.cs
For nullable members, you also have the ability to set it to null before serializing.
This is particularly useful if you want to create a single view/api model that is re-used for several API calls. The service can touch it up before setting it on the response object.
Example:
public SignInPostResponse Post(SignInPost request)
{
UserAuthentication auth = _userService.SignIn(request.Domain, true, request.Username, request.Password);
// Map domain model ojbect to API model object. These classes are used with several API calls.
var webAuth = Map<WebUserAuthentication>(auth);
// Exmaple: Clear a property that I don't want to return for this API call... for whatever reason.
webAuth.AuthenticationType = null;
var response = new SignInPostResponse { Results = webAuth };
return response;
}
I do wish there was a way to dynamically control the serialization of all members (including non-nullable) on a per endpoint fashion.

How to read this Json to controller object? Kendo UI grid server filtering

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)

Deserialize JSON in Silverlight 4

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!