Error while parsing JSON response in Windows 8 - windows-8

The following code throws error at statement :
Result res = (Result)stdserialize.ReadObject(ms);
And the error is : There was an error deserializing the object of type TrackLocation.MainPage+Result. End element 'types' from namespace '' expected. Found element 'item' from namespace ''.
HttpClient gClientRequest = new HttpClient();
System.Uri gURI = new Uri("http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true");
HttpResponseMessage gResponse = await gClientRequest.GetAsync(gURI);
string strStream = await gResponse.Content.ReadAsStringAsync();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(strStream));
DataContractJsonSerializer stdserialize = new DataContractJsonSerializer(typeof(Result));
Result res = (Result)stdserialize.ReadObject(ms);
//################################################################################################
[DataContract]
public class Address
{
[DataMember(Name = "long_name")]
public string address1;
[DataMember(Name = "short_name")]
public string shortaddress;
[DataMember(Name = "formatted_address")]
public string formattedtaddress;
[DataMember(Name = "lat")]
public string latitude;
[DataMember(Name = "long")]
public string latitude;
}
//###############################################################################################
[DataContract]
public class Result
{
[DataMember(Name = "results")]
public Address[] Results { get; set; }
[DataMember(Name = "status")]
public string Status { get; set; }
}
[DataContract]
public class Address
{
[DataMember(Name = "formatted_address")]
public string FormattedAddress;
[DataMember(Name = "address_components")]
public AddressComponent[] AddressComponents;
}
[DataContract]
public class AddressComponent
{
[DataMember(Name = "long_name")]
public string LongName;
[DataMember(Name = "short_name")]
public string ShortName;
[DataMember(Name = "types")]
public string Types;
}
any idea how to fix this issue.Any help would be greatly appreciated.

I just converted the JSON to XMl and found the types to be repeated(check screen shot below) but in your datacontract its
[DataMember(Name = "types")]
public string Types;
Just put this as
[DataMember(Name = "types")]
public string[] Types;
and it should work

Take a closer look at the JSON, your Type field of the AddressComponent should be string[] not string.
{
"results" : [
{
"address_components" : [
{
"long_name" : "285",
"short_name" : "285",
"types" : [ "street_number" ]
},
Also, you seem to have two Address classes and a result (lowercase) and Result (uppercase) class; I'm assuming those were cut-and-paste issues since they don't seem to match the JSON that's returned.

Related

How to solve may not be abstract and must be include a default constructor?

I have a database [![as this picture][1]][1]
I want to get a chart from this database and when I tried to use SQL query on the controller side, I got an error like this ;
[![this is error type][2]][2]
This is my controller code ;
public ActionResult Index2(String makineadi, DateTime? startdate, DateTime? enddate)
{
var data = entities.Database.SqlQuery<DataPoint>("SELECT Sıcaklık, Recete_Sure From Recete Where Machine_IP ='" + makineadi + "' and Tarih between'"+startdate+"' and '"+enddate+"'").ToList();
ViewBag.DataPoints = JsonConvert.SerializeObject(data);
return View();
}
And here is my class definition for getting the chart to JSON serialization;
[DataContract]
public class DataPoint
{
public DataPoint(int Sıcaklık, int Recete_Sure)
{
this.Sıcaklık = Sıcaklık;
this.Recete_Sure = Recete_Sure;
}
//Explicitly setting the name to be used while serializing to JSON.
[DataMember(Name = "Sıcaklık")]
public Nullable<int> Sıcaklık { get; set; }
//Explicitly setting the name to be used while serializing to JSON.
[DataMember(Name = "Recete_Sure")]
public Nullable<int> Recete_Sure { get; set; }
}
What should I do to fix it?
[1]: https://i.stack.imgur.com/ObwWR.png
[2]: https://i.stack.imgur.com/zQNgO.png
Add default constructor in class.
[DataContract]
public class DataPoint
{
public DataPoint()
{
}
public DataPoint(int Sıcaklık, int Recete_Sure)
{
this.Sıcaklık = Sıcaklık;
this.Recete_Sure = Recete_Sure;
}
//Explicitly setting the name to be used while serializing to JSON.
[DataMember(Name = "Sıcaklık")]
public Nullable<int> Sıcaklık { get; set; }
//Explicitly setting the name to be used while serializing to JSON.
[DataMember(Name = "Recete_Sure")]
public Nullable<int> Recete_Sure { get; set; }
}
It will resolve issue

How to resolve an error with WCF data contract -Message = "There was an error while trying to serialize parameter

I have two data contracts of same contents in two different namespaces. i have copied one datacontract to another and
passed to a particular method. but it is giving the below error and throwing exception. it is not going into that method.
Please let me know any ideas /suggestions on how to resolve this.Appreciate your help:
Exception errror:
{"Type 'System.Collections.Generic.List`1[[GlobalWcfServiceLib.TopicDetailsInfo, GlobalWcfContracts, Version=1.2.2.0, Culture=neutral,
PublicKeyToken=17c64733a9775004]]' with data contract name 'ArrayOfTopicDetailsInfo:http://CName.GlobalService/11.1/2010/11'
is not expected. Consider using a DataContractResolver or add any types not known statically to the list of
known types - for example, by using the KnownTypeAttribute attribute or by
adding them to the list of known types passed to DataContractSerializer."}
Message = "There was an error while trying to serialize parameter
http://CName.SharedServices.DBServiceLib:subscriptionDataContract.
The InnerException message was 'Type 'System.Collections.Generic.List`1
[[GlobalWcfServiceLib.TopicDetailsInfo,
GlobalWcfContra...
//////
Here is my scenario : i am copying the data from dc to new data contract as below. after copying , when i am executing the createsubscriptions method i am getting the above mentioned error. i have given the details of data contract and error attached to this question. please refer to that as well.
Method1(SubscriptionDataContracts dc)
{
SubscriptionDataContract subscriptionDataContract = new SubscriptionDataContract();
List<SubscriptionTopicInfo> topicsInfo = dc.TopicList;
List<SubscriptionTopic> newTopicsList = new List<SubscriptionTopic>();
subscriptionDataContract.ExtensionData = dc.ExtensionData;
subscriptionDataContract.UserID = dc.UserID;
for (int i = 0; i < topicsInfo.Count; i++)
{
SubscriptionTopic topic = new SubscriptionTopic();
topic.DBHandle = topicsInfo[i].DBHandle;
topic.Topic = topicsInfo[i].Topic;
topic.Target = topicsInfo[i].Target;
newTopicsList.Add(topic);
}
subscriptionDataContract.TopicList = newTopicsList;
CreateSubscriptions(subscriptionDataContract); //getting the above mentioned error in another dll after going into this method
}
////////////////////////////////
//My data contract
[DataContract(Name = "TopicDetailsInfo", Namespace = "http://CName.GlobalService")]
[Serializable]
public class TopicDetailsInfo
{
protected object topic;
protected object baseObjectType;
[DataMember]
public object BaseObjectType
{
get
{
return baseObjectType;
}
set
{
baseObjectType = value;
}
}
[DataMember]
public object TopicID
{
get
{
return topic;
}
set
{
topic = value;
}
}
static public TopicDetailsInfo CreateTopic<T, mT>(IComparable<T> objectType, IComparable<mT> objectID)
{
var topicDetails = new TopicDetailsInfo();
topicDetails.BaseObjectType = objectType;
topicDetails.TopicID = objectID;
return topicDetails;
}
}
[DataContract(Name = "SubscriptionTopicInfo", Namespace = "http://CName.GlobalService")]
[KnownType(typeof(List<TopicDetailsInfo>))]
[Serializable]
public class SubscriptionTopicInfo
{
private object topic;
private object target;
private object creator;
[DataMember]
public object Topic
{
get
{
return topic;
}
set
{
topic = value;
}
}
[DataMember]
public object Target
{
get
{
return target;
}
set
{
target = value;
}
}
[DataMember]
public object DBHandle
{
get
{
return creator;
}
set
{
creator = value;
}
}
static public SubscriptionTopicInfo CreateSubscriptions<T, mT, nT>(IList<TopicDetailsInfo> topic, IComparable<mT> target, IComparable<nT> handle)
{
var subscriptionTopic = new SubscriptionTopicInfo();
subscriptionTopic.Target = target;
subscriptionTopic.Topic = topic;
subscriptionTopic.DBHandle = handle;
return subscriptionTopic;
}
}
[DataContract(Name = "SubscriptionData", Namespace = "http://CName.GlobalService")]
[KnownType(typeof(List<SubscriptionTopicInfo>))]
[Serializable]
public class SubscriptionDataContracts : IExtensibleDataObject
{
private ExtensionDataObject extensionDataObjectValue;
[DataMember]
public string UserID
{
get;
set;
}
[DataMember]
public string ProjectID
{
get;
set;
}
[DataMember]
public string FromDiscipline
{
get;
set;
}
[DataMember]
public string ModuleID
{
get;
set;
}
[DataMember]
public string SessionID
{
get;
set;
}
[DataMember]
public List<SubscriptionTopicInfo> TopicList
{
get;
set;
}
public ExtensionDataObject ExtensionData
{
get
{
return extensionDataObjectValue;
}
set
{
extensionDataObjectValue = value;
}
}
}

Conditional member serialization based on query parameter?

I would like to control which properties from my model are serialized to my WebAPI2 JSON response, based on matching a query parameter to an attribute. I mainly want to do this to reduce bandwidth on GETs without causing a proliferation of ViewModel classes. For example:
GET /books/1?format=summary
public class Book
{
[SerializeFormat("summary")]
public int Id { get; set; }
[SerializeFormat("summary")]
public string Title { get; set; }
public string Contents { get; set; }
}
or
[SerializeFormat("summary","Id","Title")]
public class Book
{ ... }
To do this myself, I could derive all of my model classes from a custom base implementing ISerializable. In ISerializable.GetObjectData(), iterate through all properties inspecting the attributes. Not sure about performance on this idea.
Don't want to reinvent this solution, though if it already exists as a package.
One possibility would be to introduce a custom attribute JsonConditionalIncludeAttribute that can be applied to properties and fields:
[System.AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = true)]
public class JsonConditionalIncludeAttribute : System.Attribute
{
public JsonConditionalIncludeAttribute(string filterName)
{
this.FilterName = filterName;
}
public string FilterName { get; private set; }
}
Next, subclass DefaultContractResolver, override CreateProperty, and return null for properties that have at least one [JsonConditionalInclude] applied, none of which match the a filter supplied to the contract resolver:
public class JsonConditionalIncludeContractResolver : DefaultContractResolver
{
public JsonConditionalIncludeContractResolver(string filterName)
{
this.FilterName = filterName;
}
public string FilterName { get; set; }
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
// Properties without JsonConditionalIncludeAttribute applied are serialized unconditionally.
// Properties with JsonConditionalIncludeAttribute are serialized only if one of the attributes
// has a matching filter name.
var attrs = property.AttributeProvider.GetAttributes(typeof(JsonConditionalIncludeAttribute), true);
if (attrs.Count > 0 && !attrs.Cast<JsonConditionalIncludeAttribute>().Any(a => a.FilterName == FilterName))
return null;
return property;
}
}
Finally, when serializing your class to JSON, set JsonSerializerSettings.ContractResolver equal to your custom contract resolver, initializing the FilterName from your web request, for instance:
public class TestClass
{
public string Property1 { get; set; }
[JsonConditionalInclude("summary")]
[JsonConditionalInclude("title")]
public string Property2 { get; set; }
[JsonConditionalInclude("summary")]
public string Property3 { get; set; }
[JsonConditionalInclude("title")]
[JsonConditionalInclude("citation")]
public string Property4 { get; set; }
[JsonConditionalInclude("citation")]
public string Field1;
public static void Test()
{
var test = new TestClass { Property1 = "a", Property2 = "b", Property3 = "c", Property4 = "d", Field1 = "e" };
Test(test, "summary"); // Prints "a", "b" and "c"
Test(test, "title"); // Prints "a", "b" and "d".
Test(test, "citation");// Prints "e", "a" and "d"
Test(test, null); // Prints "e", "a", "b", "c" and "d".
}
public static string Test(TestClass test, string webRequestFormat)
{
var settings = new JsonSerializerSettings { ContractResolver = new JsonConditionalIncludeContractResolver(webRequestFormat) };
var json = JsonConvert.SerializeObject(test, Formatting.Indented, settings);
Debug.WriteLine(json);
return json;
}
}
The contract resolver will apply to all classes being serialized, not just the root class, which looks to be what you want.

Serialize Partial DataContract

I have a DataContract that looks like:
[DataContract(Name = User.Root, Namespace = "")]
public class RegisterUser
{
[DataMember(Name = User.EmailAddress)]
public string EmailAddress { get; set; }
[DataMember(Name = User.UserName)]
public string UserName { get; set; }
[DataMember(Name = User.Password)]
public string Password { get; set; }
[DataMember(Name = User.FirstName)]
public string FirstName { get; set; }
[DataMember(Name = User.LastName)]
public string LastName { get; set; }
[DataMember(Name = User.PhoneNumber)]
public string PhoneNumber { get; set; }
[DataMember(Name = "RequestMessage")]
public string RequestMsg { get; set; }
}
And I would like to get the elements out of it. So instead of
<ROOT> <Element1/>...</ROOT>. I would just like to get <Element1/> (for partial xsd validation).
I thought I could use this function:
public static string Serialize<T>(T obj)
{
DataContractSerializer ser = new DataContractSerializer(obj.GetType());
String text;
using (MemoryStream memoryStream = new MemoryStream())
{
ser.WriteObject(memoryStream, obj);
byte[] data = new byte[memoryStream.Length];
Array.Copy(memoryStream.GetBuffer(), data, data.Length);
text = Encoding.UTF8.GetString(data);
}
return text;
}
and just pass it
string str = Serialize(test.EmailAddress);
That works great but the xml looks like:
"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">myemail.com</string>"
I lost the DataMember info. How can I retain that as well?
Use WriteObjectContent instead of WriteObject:
http://msdn.microsoft.com/en-us/library/ms573853.aspx

Does Order Matter in the XML Read by the DataContractSerializer?

I have the following code:
[DataContract(Namespace = "")]
public class User
{
[DataMember]
public string UserName { get; set; }
[DataMember]
public string FullName { get; set; }
}
//Deserialization test
public void Test()
{
//CASE 1.
//string xml = "<User><UserName>john</UserName>" +
// "<FullName>John Lennon</FullName></User>";
//CASE 2.
string xml = "<User><FullName>John Lennon</FullName>" +
"<UserName>john</UserName></User>";
byte[] byteArray = Encoding.UTF8.GetBytes(xml);
User user = null;
using (MemoryStream stream = new MemoryStream(byteArray))
{
DataContractSerializer serializer =
new DataContractSerializer(typeof(User), "User", "");
user = (User)serializer.ReadObject(stream);
}
}
In case 1, FullName property isn't deserialized, but in case 2 it is deserialized properly. Why?
Because order is significant. Alphabetic order is used unless you specify the order in your DataMember attributes.
This is explained in this MSDN article.
In general, it's a good practice to always explicitly specify Order on your DataMember attributes:
[DataMember(IsRequired=true, Order=0)]
public string FullName { get; set; }
[DataMember(IsRequired=true, Order=1)]
public string UserName { get; set; }