public class ParentData :ObservableRangeCollection<ChildData>
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class ChildData
{
public string ChildName { get; set; }
public int ChildAge { get; set; }
}
List<ParentData> lstParent = new List<ParentData>();
ParentData pData = new ParentData();
pData.Name = "John";
pData.Id = 111;
pData.Age = 45;
ChildData childData = new ChildData();
childData.ChildAge = 12;
childData.ChildName = "tommy";
pData.Add(childData);
lstParent.Add(pData);
string Json = JsonConvert.SerializeObject(lstParent, Formatting.None);
Upon serializing, the ParentData does not get serialized
[[{"ChildName":"tommy","ChildAge":12,"ErrorMessage":null}]]
How do I serialize the Parent Node?
Related
I am using DropDownlist in order to get country of all the world. I have attached the file(country_list.txt) using srcFilePath. The error i am getting is "There is no ViewData item of type 'IEnumerable' that has the key 'SelectedCountryId'.What could be an issue, because my EditFormTrainingRegViewModel does have this field SelectedCountry as a primary key. Its been declared as public int? SelectedCountryId {get;set;}
// List for countries.
private IEnumerable<SelectListItem> GetCountryList()
{
SelectList listcn = null;
try
{
var list = this.LoadData().Select(p => new SelectListItem
{
Value = p.Country_Id.ToString(),
Text = p.Country_Name
});
listcn = new SelectList(list, "Value", "Text");
}catch(Exception ex)
{
throw ex;
}
return listcn;
}
public ActionResult DropDownSelect()
{
EditTrainingRegFormViewModel model = new EditTrainingRegFormViewModel();
model.SelectedCountryId = 0;
this.ViewBag.CountryList = this.GetCountryList();
return this. View(model);
}
// Loading data for country list.
private List<EditTrainingRegFormViewModel> LoadData()
{
List<EditTrainingRegFormViewModel> lst = new List<EditTrainingRegFormViewModel>();
try
{
string line = string.Empty;
string srcFilePath = "Content/files/country_list.txt";
var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
var fullPath = Path.Combine(rootPath, srcFilePath);
string filePath = new Uri(fullPath).LocalPath;
StreamReader src = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));
// while to read the file
while((line = src.ReadLine()) !=null) {
EditTrainingRegFormViewModel infoLst = new EditTrainingRegFormViewModel();
string[] info = line.Split(',');
//Setting
infoLst.Country_Id = Convert.ToInt32(info[0].ToString());
infoLst.Country_Name = info[1].ToString();
lst.Add(infoLst);
}
src.Dispose();
src.Close();
}catch(Exception ex)
{
Console.Write(ex);
}
return lst;
}
//View
#Html.DropDownListFor(m=>m.SelectedCountryId, this.ViewBag.CountryList as SelectList, new {#class = "form-control"})
// Model class
public class EditTrainingRegFormViewModel
{
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Position { get; set; }
public string Company { get; set; }
public string Address { get; set; }
[Display(Name = "Choose country")]
public int ? SelectedCountryId { get; set; }
public string Code { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Cell_Number { get; set; }
public List<string> Dietary_requirement { get; set; }
public string Email { get; set; }
public int Country_Id { get; set; }
public string Country_Name { get; set; }
}
want to parse a JSON string in combobox to 'text'. The response is something like
How can I parse the JSON and extract its 'text' values?
var restClient = new RestClient("https://cbsservis.tkgm.gov.tr/megsiswebapi.v2/api/idariYapi/ilListe");
var restRequest = new RestRequest(Method.GET);
var restResponse = restClient.Execute(restRequest);
restRequest.AddHeader("Accept", "text/json");
var jArray = Newtonsoft.Json.Linq.JObject.Parse(restResponse.Content);
dynamic jsonResponse = JsonConvert.DeserializeObject(restResponse.Content);
dynamic jsonResponse2 = JsonConvert.DeserializeObject<RootObject>(string JObject);`
Your response can be represented by classes like this:
public class Rootobject
{
public Feature[] features { get; set; }
public string type { get; set; }
public Crs crs { get; set; }
}
public class Crs
{
public string type { get; set; }
public Properties properties { get; set; }
}
public class Properties
{
public string name { get; set; }
}
public class Feature
{
public string type { get; set; }
public Geometry geometry { get; set; }
public Properties1 properties { get; set; }
}
public class Geometry
{
public string type { get; set; }
public object[][][] coordinates { get; set; }
}
public class Properties1
{
public string text { get; set; }
public int id { get; set; }
}
Hence your code can be changed to:
var restClient = new RestClient("https://cbsservis.tkgm.gov.tr/megsiswebapi.v2/api/idariYapi/ilListe");
var restRequest = new RestRequest(Method.GET);
var restResponse = restClient.Execute(restRequest);
restRequest.AddHeader("Accept", "text/json");
var obj = JsonConvert.DeserializeObject<Rootobject>(restResponse.Content);
You will receive the object like this:
And then you can loop through properties to get desired text.
I'm fairly new to the awesomeness that is JSON - I'm using the DataContractJsonSerializer. I cannot get the multiple instances of the Customer objects into the list.
The Attributes work as expected but there are no Customer objects in my List..??
{
"#attributes":
{"count":"2",
"offset":"0",
"limit":"100"
},
"Customer":
{
"firstName":"cust ",
"lastName":"one",
"title":"Owner",
"company":"CustOne Plants",
"companyRegistrationNumber":"",
"vatNumber":"",
"creditAccountID":"1",
"customerTypeID":"4",
"discountID":"0",
"taxCategoryID":"0",
"customerID":"1",
"createTime":"2017-06-19T23:36:11+00:00",
"timeStamp":"2017-06-20T18:55:11+00:00",
"archived":"false"
}
"Customer":
{
"firstName":"cust ",
"lastName":"two",
"title":"Owner",
"company":"CustTwo House of Games",
"companyRegistrationNumber":"",
"vatNumber":"",
"creditAccountID":"1",
"customerTypeID":"4",
"discountID":"0",
"taxCategoryID":"0",
"customerID":"1",
"createTime":"2017-06-19T23:36:11+00:00",
"timeStamp":"2017-06-20T18:55:11+00:00",
"archived":"false"
}
}
.NET code:
StreamReader stream = new StreamReader(#"C:\TMC Projects\PotteryManufacturing\CustomerJSON.txt");
string text = stream.ReadToEnd();
stream.Close();
byte[] byteArray = Encoding.UTF8.GetBytes(text);
MemoryStream stream1 = new MemoryStream(byteArray);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(CustomersRoot));
var varInfo = serializer.ReadObject(stream1) as CustomersRoot;
stream1.Close();
and finally my classes/data contracts/data members:
[DataContract]
public class CustomersRoot
{
private List<Customer> m_Customers;
public CustomersRoot() { this.Customer = new List<Customer>(); }
[DataMember(Name ="#attributes")]
public Attributes attrs { get; set; }
[DataMember(Name = "Customer")]
public List<Customer> Customer
{
get { return m_Customers; }
set { m_Customers = value; }
}
}
[DataContract]
public class Customer
{
[DataMember(Name ="firstName")]
public string firstName { get; set; }
[DataMember(Name = "lastName")]
public string lastName { get; set; }
[DataMember(Name = "title")]
public string title { get; set; }
[DataMember(Name = "company")]
public string company { get; set; }
[DataMember(Name = "companyRegistrationNumber")]
public string companyRegistrationNumber { get; set; }
[DataMember(Name = "vatNumber")]
public string vatNumber { get; set; }
[DataMember(Name = "creditAccountID")]
public int creditAccountID { get; set; }
[DataMember(Name = "customerTypeID")]
public int customerTypeID { get; set; }
[DataMember(Name = "discountID")]
public int discountID { get; set; }
[DataMember(Name = "taxCategoryID")]
public int taxCategoryID { get; set; }
[DataMember(Name = "customerID")]
public int customerID { get; set; }
[DataMember(Name = "createTime")]
public string createTime { get; set; }
[DataMember(Name = "timeStamp")]
public string timeStamp { get; set; }
[DataMember(Name = "archived")]
public bool archived { get; set; }
}
[DataContract]
public class Attributes
{
[DataMember(Name = "count")]
public int count { get; set; }
[DataMember(Name = "offset")]
public int offset { get; set; }
[DataMember(Name = "limit")]
public int limit { get; set; }
}
I figured out what's going on here - the call can sometimes return an array of Customer objects (not formatted correctly above) OR a single instance of the object. When the web service returns a single Customer instance, the List code does not work. I will have to check on how to deal w/ this issue.
I Have json file :
Google Maps Api - place Json
I want Parsing Json using System.Runtime.Serialization;
I can create 3 class :
public class Places
{
[DataMember(Name = "geometry")]
public string Geometry
{
get;
set;
}
[DataMember(Name = "location")]
public string Location { get; set; }
[DataMember(Name = "lat")]
public string Latitude { get; set; }
[DataMember(Name = "lng")]
public string Longitude { get; set; }
[DataMember(Name = "icon")]
public string Icon { get; set; }
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "photo")]
public string Photo { get; set; }
[DataMember(Name = "rating")]
public string Rating { get; set; }
[DataMember(Name = "reference")]
public string Reference { get; set; }
[DataMember(Name = "types")]
public string Types { get; set; }
[DataMember(Name = "vicinity")]
public string Vicinity { get; set; }
}
public class AppConstants
{
public static String baseUri = "https://maps.googleapis.com/maps/api/place/search/json?location=";
}
public class PlaceToMap
{
public GeoCoordinate Coordinate { get; set; }
public string Info { get; set; }
}
[DataContract]
public class PlacesList
{
[DataMember(Name ="results")]
public List<Places> PlaceList { get; set; }
}
MainPage.xaml.cs :
private void updateMap(PlacesList googlePlaceApiRespone)
{
int totalRecords = googlePlaceApiRespone.PlaceList.Count();
try
{
ObservableCollection<PlaceToMap> placeToMapObjs = new ObservableCollection<PlaceToMap>();
for (int index = 0; index < totalRecords; index++)
{
placeToMapObjs.Add(new PlaceToMap()
{
Coordinate = new GeoCoordinate(Convert.ToDouble(googlePlaceApiRespone.PlaceList.ElementAt(index).Latitude),
Convert.ToDouble(googlePlaceApiRespone.PlaceList.ElementAt(index).Longitude)),
Info = googlePlaceApiRespone.PlaceList.ElementAt(index).Name + Environment.NewLine + googlePlaceApiRespone.PlaceList.ElementAt(index).Vicinity
});
}
ObservableCollection<DependencyObject> children = MapExtensions.GetChildren(myMap);
var obj = children.FirstOrDefault(x => x.GetType() == typeof(MapItemsControl)) as MapItemsControl;
obj.ItemsSource = placeToMapObjs;
myMap.SetView(new GeoCoordinate(Convert.ToDouble(currentLatitude), Convert.ToDouble(currentLongitude)), 16);
}
catch (Exception)
{
}
}
But can't no show in pushpin.
toolkit:Pushpin GeoCoordinate="{Binding Coordinate}" Content="{Binding Info}"
I am trying to put some distributed caching into play, I'm using this indeXus.Net Shared Cache .
It Requires that the object being cached is serializable, which it is here is the class object.
[Serializable]
public class Members
{
public Members()
{}
public Members(string aspnetusername, string aspnetpassword,
string emailaddr,string location)
: this(0,0,aspnetusername, aspnetpassword,emailaddr,DateTime.Now, location,
0,0,DateTime.Now,DateTime.Now,DateTime.Now,false)
{ }
public Members(Int64? row,int memberid, string aspnetusername, string aspnetpassword,
string emailaddr,DateTime datecreated, string location, int daimokugoal, int previewimageid,
DateTime lastdaimoku, DateTime lastnotifed, DateTime lastactivitydate, bool isactivated)
{
this.Row = row;
this.MemberID = memberid;
this.Aspnetusername = aspnetusername;
this.Aspnetpassword = aspnetpassword;
this.EmailAddr = emailaddr;
this.DateCreated = datecreated;
this.Location = location;
this.DaimokuGoal = daimokugoal;
this.PreviewImageID = previewimageid;
this.LastDaimoku = lastdaimoku;
this.LastNotefied = lastnotifed;
this.LastActivityDate = lastactivitydate;
this.IsActivated = this.IsActivated;
this.Details = new LazyList<MemberDetails>();
this.Blogs = new LazyList<MemberBlogs>();
this.Daimoku = new LazyList<MemberDaimoku>();
this.Determinations = new LazyList<MemberDeterminations>();
this.Encouragements = new LazyList<MemberEncouragements>();
this.Entries = new LazyList<MemberEntries>();
this.Friends = new LazyList<MemberFriends>();
this.Stats = new LazyList<MemberStats>();
}
public Int64? Row { get; set; }
public int MemberID { get; set; }
public string Aspnetusername { get; set; }
public string Aspnetpassword { get; set; }
public string EmailAddr { get; set; }
public DateTime DateCreated { get; set; }
public string Location { get; set; }
public int DaimokuGoal { get; set; }
public int PreviewImageID { get; set; }
public DateTime LastDaimoku { get; set; }
public DateTime LastNotefied { get; set; }
public DateTime LastActivityDate { get; set; }
public bool IsActivated { get; set; }
public LazyList<MemberDetails> Details { get; set; }
public LazyList<MemberBlogs> Blogs { get; set; }
public LazyList<MemberDaimoku> Daimoku { get; set; }
public LazyList<MemberDeterminations> Determinations { get; set; }
public LazyList<MemberEncouragements> Encouragements { get; set; }
public LazyList<MemberEntries> Entries { get; set; }
public LazyList<MemberFriends> Friends { get; set; }
public LazyList<MemberStats> Stats { get; set; }
}
The LINQtoSql is this that populates this class.
public IQueryable<Members> GetMemberInfo()
{
using (var t = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
{
var results = from m in _datacontext.ViewMembers
let details = GetMemberDetails(m.MemberID)
let determinations = GetMemberDeterminations(m.MemberID)
let daimoku = GetMemberDaimoku(m.MemberID)
let entries = GetMemberEntries(m.MemberID)
let blogs = GetMemberBlogs(m.MemberID)
let encouragements = GetMemberEncouragements(m.MemberID)
let friends = GetMemberFriends(m.MemberID)
let points = GetMemberStats(m.MemberID)
select new Members
{
Row = m.Row,
MemberID = m.MemberID,
Aspnetusername = m.Aspnetusername,
Aspnetpassword = m.Aspnetpassword,
EmailAddr = m.EmailAddr,
DateCreated = m.DateCreated,
Location = m.Location,
DaimokuGoal = m.DaimokuGoal,
PreviewImageID = m.PreviewImageID,
LastDaimoku = m.LastDaimoku.Value,
LastNotefied = m.LastNotefied.Value,
LastActivityDate = m.LastActivityDate.Value,
IsActivated = m.IsActivated,
Details = new LazyList<MemberDetails>(details),
Determinations = new LazyList<MemberDeterminations>(determinations),
Daimoku = new LazyList<MemberDaimoku>(daimoku),
Entries = new LazyList<MemberEntries>(entries),
Blogs = new LazyList<MemberBlogs>(blogs),
Encouragements = new LazyList<MemberEncouragements>(encouragements),
Friends = new LazyList<MemberFriends>(friends),
Stats = new LazyList<MemberStats>(points)
};
return results;
}
}
But for some reason I am getting this error
System.Runtime.Serialization.SerializationException: Type 'System.Data.Linq.DataQuery`1[[DaimokuBeta.MVC.Data.MemberDetails, DaimokuBeta.MVC.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' in Assembly 'System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
MemberDetails is serializable too..so not sure why it thinks it can't be serialized
Any ideas?
I believe that it's your LazyList implementation that cannot be serialized because the exception is telling us that the generic type DataQuery (from assembly System.Data.Linq) is not serializable. Is this type connected to your LazyList in any way?
If you are trying to cache the Members DTO (data transfer object) it's probably not a good idea to be applying lazy loading because it may only be executed in a very unpredictable moment.
Cache should usually be applied to data that has already been loaded/computed. Otherwise there may not be much point in using cache.