Issue serializing / deserializing a custom object with double values - c#

Trying to deserialize an instance of this class
[Serializable]
public class InstalledMeter : ISerializable
{
public string Description { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Description", Description);
info.AddValue("Latitude", Latitude);
info.AddValue("Longitude", Longitude);
}
}
The instance:
new InstalledMeter {Description = "Something", Latitude = 0.0, Longitude = 0.0};
My Serialization methods
public static class SerializeString
{
public static string SerializeObject<T>(this T toSerialize)
{
var xmlSerializer = new XmlSerializer(toSerialize.GetType());
var textWriter = new StringWriter();
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
public static T XmlDeserializeFromString<T>(this string objectData)
{
return (T)XmlDeserializeFromString(objectData, typeof(T));
}
public static object XmlDeserializeFromString(string objectData, Type type)
{
var serializer = new XmlSerializer(type);
object result;
using (TextReader reader = new StringReader(objectData))
{
result = serializer.Deserialize(reader);
}
return result;
}
}
But when I serialize the object it has these values

(guessing an answer based on your previous question - Error passing parameters to mvvmcross viewmodels)
If you are doing this in MvvmCross, then I would avoid this xml problem altogether and just use JSON serialization
var jsonText = JSONConvert.SerializeObject(installedMeter);
and
var installedMeter = JSONConvert.DeserializeObject<InstalledMeter>(jsonText);
using just:
public class InstalledMeter
{
public string Description { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
}

Related

How to deserialize a list inside of a list with list type Interface?

While deserializing, I get this error:
Error getting value from 'tasksToDo' on 'StudentHousingFramework.Modules.Room'.
System.NullReferenceException: Object reference not set to an instance of an object.
I'm trying to deserialize a list of interfaces that have a list of type interface (different ones) inside.
tasksToDo is a List<Interface> on the class and it's, to my understanding, what's causing the issue.
The way I deserialize is via this classes:
public void Serealise<T>(string nameList, List<T> list)
{
path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, nameList);
string jsonString = JsonConvert.SerializeObject(list, Formatting.Indented, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
TypeNameHandling = TypeNameHandling.Auto
}); ;
File.WriteAllText(path, jsonString);
}
public List<IAccount>? DeserealiseRoom(string list)
{
path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, list);
if (File.Exists(path))
{
var file = File.ReadAllText(path);
return JsonConvert.DeserializeObject<List<IAccount>>(file, new JsonSerializerSettings
{
ReferenceLoopHandling= ReferenceLoopHandling.Ignore,
TypeNameHandling= TypeNameHandling.Auto,
});
}
return null;
}
This is the class room that inherits from the interface that characterises the list:
public class Room : IAccount
{
public Room()
{
}
[JsonIgnore]
public List<ITask> tasksToDo
{
get
{
return factory.manager.tasks.FindAll(w => w.claimer == this);
}
}
public Login login { get; set; }
public bool isOccupied { get; private set; } = true;
public int id { get; set; }
public string name
{
get
{
return "Room " + id;
}
}
public Json json { get; set; } = new Json();
private Factory factory { get; set; }
public Room(Factory factory, int id)
{
this.factory = factory;
this.id = id;
login = new Login();
}
}
What can I do to solve this issue?

Json not serializing all object in Azure

I have POCO which is as simple as
public partial class Member
{
public int ID { get; set; }
[Required]
[StringLength(100)]
public string MemberId { get; set; }
public DateTime CreatedOn { get; set; }
[Required]
[StringLength(100)]
public string FirstName { get; set; }}
and a Add command which looks like this
public class AddMemberCommand : ICommand
{
public AddMemberCommand(Member member )
{
ID = Guid.NewGuid();
MemberData = member;
}
public Member MemberData { get; private set; }
public Guid ID { get; }
public string CommandName
{
get { return "AddMemberCommand"; }
}
}
which inherits from
public interface ICommand
{
/// <summary>
/// Gets the command identifier.
/// </summary>
Guid ID { get; }
string CommandName { get; }
}
Now I send this code to a method which initializes Newton Json's serializing setting class with some parameters to return an object. The serializer looks like this
public class JsonTextSerializer
{
private readonly JsonSerializer _serializer;
public JsonTextSerializer()
{
_serializer = JsonSerializer.Create(new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
});
}
public void Serialize(TextWriter writer, object graph)
{
var jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
_serializer.Serialize(jsonWriter, graph);
writer.Flush();
}
public object Deserialize(TextReader reader)
{
var jsonReader = new JsonTextReader(reader);
try
{
return this._serializer.Deserialize(jsonReader);
}
catch (JsonSerializationException e)
{
// Wrap in a standard .NET exception.
throw new SerializationException(e.Message, e);
}
}
}
The serializer is used to convert the command into a payload for the brokered message as shown below
private BrokeredMessage CreateMessage(POCOS.Member member)
{
var serializer = new JsonTextSerializer();
var command = new AddMemberCommand(member);
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
serializer.Serialize(writer, command);
stream.Position = 0;
BrokeredMessage message = new BrokeredMessage(stream, true);
return message;
}
and there is a another method which receives the method
private POCOS.Member GetPocoFromMessage(BrokeredMessage message)
{
ITextSerializer serializer = new JsonTextSerializer();
AddMemberCommand command;
using (var stream = message.GetBody<Stream>())
{
using (var reader = new StreamReader(stream))
{
var payload = serializer.Deserialize(reader);
command = payload as AddMemberCommand;
}
}
return command.MemberData;
}
The issue is on deserializing some properties ( ID, CommandName) are filled with value except for MemberData which is null.
I can read the stream (by doing a reader.ReadToEnd()) and see it was transferred over the wire but Json can't deserialize all its object
At one time I also thought it perhaps picks only fields in the Interface but that's not the case
Your MemberData property has a private setter. Since the serializer needs access to the property externally, this setter should be public.

Class Serialization To XML

Given the following class design:
public class AllUserCollections
{
public List<UserCollection> UserCollections { get; set; }
public AllUserCollections()
{
this.UserCollections = new List<UserCollection> ();
}
}
public class UserCollection
{
public string UserGroup { get; set; }
public Dictionary<int,User> Users { get; set; }
public UserCollection(string userGroup)
{
this.UserGroup = userGroup;
this.Users = new Dictionary<int, User> ();
}
}
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public AgeGroup UserAgeGroup { get; set; }
}
public enum AgeGroup
{
Twenties,
Thirties,
Fourties,
}
How can I serialize this to XML using my existing serialization class?
public static class HardDriveService
{
private static string docsFolderPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
private const string fileName = "AllUserCollections.xml";
private static string filePath = Path.Combine(docsFolderPath, fileName);
private static bool FileExists(string fullFilePath)
{
if (File.Exists (fullFilePath))
return true;
return false;
}
public static void Save(AllUserCollections allUserCollections)
{
if (FileExists(filePath))
{
File.Delete (filePath);
}
XmlSerializer serializer = new XmlSerializer(allUserCollections.GetType());
using(StreamWriter writer = new StreamWriter(filePath))
{
serializer.Serialize(writer.BaseStream, allUserCollections);
}
}
public static AllUserCollections Read()
{
AllUserCollections allUserCollections = new AllUserCollections();
XmlSerializer serializer = new XmlSerializer(allUserCollections.GetType());
if (FileExists(filePath))
{
StreamReader reader = new StreamReader(filePath);
object deserialized = serializer.Deserialize(reader.BaseStream);
allUserCollections = (AllUserCollections)deserialized;
}
return allUserCollections;
}
}//End of class.
ISSUES
My code seems to fail on this line -
XmlSerializer serializer = new XmlSerializer(allUserCollections.GetType());
I wonder if it's to do with the class needing to be explicitly marked as "serializable"? How would I do this?
Usage
This code will run on an iphone and save/read directly from an app to XML on the iPhone hard drive.
XMLSerializer doesn't support Dictionary out of the box. Your UserCollection class has a Dictionary. See this link for a workaround.
Why doesn't XmlSerializer support Dictionary?
Other than that the XMLSerializer requires that your classes have default constructors (UserCollection and User don't) and each of them must have the [Serializable] attribute.
You could use XElement to build up an XML format. You could use them along the following lines:
public static XElement ToXml(this User user)
{
if (user == null)
{
throw new ArgumentException("User can not be null.");
}
XElement userElement = new XElement("User");
userElement.Add(new XElement("ID", user.ID));
userElement.Add(new XElement("Name", user.Name));
userElement.Add(new XElement("Location", user.Location));
userElement.Add(new XElement("UserAgeGroup", user.UserAgeGroup));
return userElement;
}
public static string ToXml(this UserCollection userCollection)
{
if (userCollection == null)
{
throw new ArgumentException("UserCollection can not be null.");
}
XElement userCollectionElement = new XElement("UserCollection");
userCollectionElement.Add(new XElement("UserGroup", userCollection.UserGroup));
userCollectionElement.Add(new XElement("Users",
userCollection.Users.Select(x => new XElement("User", x.ToXml()));
return userCollectionElement;
}
Calling .ToString() on an XElement should give you an xml-formatted string.
FULL WORKING SOLUTION
Data Model
using System;
using System.Collections.Generic;
namespace iPhoneHardDriveCRUDPrototype
{
[Serializable]
public class AllUserCollections
{
public List<UserCollection> UserCollections { get; set; }
public AllUserCollections()
{
this.UserCollections = new List<UserCollection> ();
}
}
[Serializable]
public class UserCollection
{
public string UserGroup { get; set; }
public SerializableDictionary<int,User> Users { get; set; }
public UserCollection()
{
this.Users = new SerializableDictionary<int, User> ();
}
public UserCollection(string userGroup)
{
this.UserGroup = userGroup;
this.Users = new SerializableDictionary<int, User> ();
}
}
[Serializable]
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public AgeGroup UserAgeGroup { get; set; }
public User()
{
}
}
[Serializable]
public enum AgeGroup
{
Twenties,
Thirties,
Fourties,
}
}
Serializable Dictionary
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace iPhoneHardDriveCRUDPrototype
{
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
return;
while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement("value");
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
}//End of Class....
}
Serializer
using System;
using System.IO;
using System.Xml.Serialization;
using System.Reflection;
using System.Collections.Generic;
namespace iPhoneHardDriveCRUDPrototype
{
public static class HardDriveService
{
private static string docsFolderPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
private const string fileName = "AllUserCollections.xml";
private static string filePath = Path.Combine(docsFolderPath, fileName);
private static bool FileExists(string fullFilePath)
{
if (File.Exists (fullFilePath))
return true;
return false;
}
public static void Save(AllUserCollections allUserCollections)
{
if (FileExists(filePath))
{
File.Delete (filePath);
}
XmlSerializer serializer = new XmlSerializer(allUserCollections.GetType());
using(StreamWriter writer = new StreamWriter(filePath))
{
serializer.Serialize(writer.BaseStream, allUserCollections);
}
}
public static AllUserCollections Read()
{
AllUserCollections allUserCollections = new AllUserCollections();
XmlSerializer serializer = new XmlSerializer(allUserCollections.GetType());
if (FileExists(filePath))
{
StreamReader reader = new StreamReader(filePath);
object deserialized = serializer.Deserialize(reader.BaseStream);
allUserCollections = (AllUserCollections)deserialized;
}
return allUserCollections;
}
}//End of class.
}
Here you have 2 choices XmlSerializer(which will not work with Dictionary or List type deserialization ) or you can use DataContractSerializer which added in .net 3.0 and has a lot advantages here are few: form this post
optimized for speed (about 10% faster than XmlSerializer, typically)
in "opt-in" - only stuff you specifically mark as [DataMember] will be serialized
doesn't support XML attributes (for speed reasons)
Note : you should add reference to the C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\System.Runtime.Serialization.dll
//to serialize
SerializeHelper.Serialize("your filename" ,new AllUserCollections());
// deserialize
var usertCollections = SerializeHelper.Deserialize<AllUserCollections>("yourfile name");
//code
[DataContract]
public class AllUserCollections
{
public List<UserCollection> UserCollections { get; set; }
public AllUserCollections()
{
this.UserCollections = new List<UserCollection>();
}
}
[DataContract()]
public class UserCollection
{
[DataMember]
public string UserGroup { get; set; }
[DataMember]
public Dictionary<int, User> Users { get; set; }
public UserCollection(string userGroup)
{
this.UserGroup = userGroup;
this.Users = new Dictionary<int, User>();
}
}
[DataContract()]
public class User
{ [DataMember]
public int ID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Location { get; set; }
[DataMember]
public AgeGroup UserAgeGroup { get; set; }
}
[DataContract]
public enum AgeGroup
{
Twenties,
Thirties,
Fourties,
}
public static class SerializeHelper
{
public static void Serialize<T>(string fileName, T obj)
{
using (FileStream writer = new FileStream(fileName, FileMode.Create))
{
DataContractSerializer ser =
new DataContractSerializer(typeof(T));
ser.WriteObject(writer, obj);
writer.Close();
}
}
public static T Deserialize<T>(string fileName)
{
T des;
using (FileStream fs = new FileStream(fileName,FileMode.Open))
{
XmlDictionaryReader reader =
XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
DataContractSerializer ser = new DataContractSerializer(typeof(T));
des =
(T)ser.ReadObject(reader, true);
reader.Close();
fs.Close();
}
return des;
}
}

DataContract Serialization of List<> containing objects

While developing a test case to understand serialization, I've run into what looks like a straighforward problem but am unable to figure out. I want to be able to add multiple objects to a list<> and then serialize that list (in this case I'm using DataContractJsonSerializer). After creating the objects (node1 and node2), I want to add them to a List<> (cn) and serialize it. However, I get an invalid argument error when adding node1 and node2 ("cannot convert from 'JSON_test.Aspirate' to 'JSON_test.CompositeNode'). I believe it is a matter of letting the array know about the base types, but I don't know how to do that, or if in fact that is the issue (still very new to all this).
Thank you.
namespace JSON_test
{
class Program
{
static void Main(string[] args)
{
Aspirate node1 = new Aspirate(25,40);
Dispense node2 = new Dispense(32,50);
ObjectToSerialize cn = new ObjectToSerialize();
cn.CompositeNode.Add (node1);
cn.CompositeNode.Add (node2);
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ObjectToSerialize));
ser.WriteObject(stream1, cn.CompositeNode);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
Console.WriteLine(sr.ReadToEnd());
Console.ReadLine();
}
}
[DataContract]
public class ObjectToSerialize
{
private List<CompositeNode> compNode;
[DataMember]
public List<CompositeNode> CompositeNode
{
get {return this.CompositeNode;}
set { this.compNode = value; }
}
public ObjectToSerialize()
{
}
}
[DataContract]
public class CompositeNode
{
}
[DataContract]
public class Aspirate
{
[DataMember]
public string NodeName = "Aspirate";
[DataMember]
public double ZTravelHt;
[DataMember]
public double IndexHt;
public Aspirate(double ZTravelHt, double IndexHt)
{
this.ZTravelHt = ZTravelHt;
this.IndexHt = IndexHt;
}
}
[DataContract]
public class Dispense
{
[DataMember]
public string NodeName = "Dispense";
[DataMember]
public double ZTravelHt;
[DataMember]
public double IndexHt;
public Dispense(double ZTravelHt, double IndexHt)
{
this.ZTravelHt = ZTravelHt;
this.IndexHt = IndexHt;
}
}
}
UPDATE
namespace JSON_test
{
class Program
{
static void Main(string[] args)
{
Aspirate node1 = new Aspirate(25,40);
Dispense node2 = new Dispense(32,50);
ObjectToSerialize cn = new ObjectToSerialize();
cn.CompositeNode.Add (node1);
cn.CompositeNode.Add (node2);
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ObjectToSerialize),
new Type[] {typeof (Aspirate), typeof (Dispense)});
ser.WriteObject(stream1, cn.CompositeNode);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
Console.WriteLine(sr.ReadToEnd());
Console.ReadLine();
}
}
[DataContract]
[KnownType(typeof(Aspirate))]
[KnownType(typeof(Dispense))]
public class ObjectToSerialize
{
private List<CompositeNode> compNode = new List<CompositeNode>();
[DataMember]
public List<CompositeNode> CompositeNode
{
get {return this.compNode;}
set { this.compNode = value; }
}
public ObjectToSerialize()
{
}
}
[DataContract]
[KnownType(typeof(Aspirate))]
[KnownType(typeof(Dispense))]
public class CompositeNode
{
}
[DataContract]
public class Aspirate : CompositeNode
{
[DataMember]
public string NodeName = "Aspirate";
[DataMember]
public double ZTravelHt;
[DataMember]
public double IndexHt;
public Aspirate(double ZTravelHt, double IndexHt)
{
this.ZTravelHt = ZTravelHt;
this.IndexHt = IndexHt;
}
}
[DataContract]
public class Dispense : CompositeNode
{
[DataMember]
public string NodeName = "Dispense";
[DataMember]
public double ZTravelHt;
[DataMember]
public double IndexHt;
public Dispense(double ZTravelHt, double IndexHt)
{
this.ZTravelHt = ZTravelHt;
this.IndexHt = IndexHt;
}
}
}
You can add a KnownTypeAttribute to the ObjectToSerialize to let the serializer know which types to expect:
[DataContract]
[KnownType(typeof(Aspirate))]
[KnownType(typeof(Dispense))]
public class ObjectToSerialize
{
....
}
I understand that the classes Aspirate and Dispense are derived from CompositeNode? This is not clear from your code example.
You have an error in your code by the way:
get {return this.CompositeNode;}
should be:
get {return this.compNode;}
Update: in resoponse to your question in the comments: you have to intialize the collection inside a constructor of ObjectToSerialize:
public ObjectToSerialize()
{
this.compNode = new List<CompositeNode>();
}
Update 2: The line that is wrong is:
ser.WriteObject(stream1, cn.CompositeNode);
This should be:
ser.WriteObject(stream1, cn);
By the way, you can just write this:
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ObjectToSerialize));
You already defined the known types by using attributes. Adding the known types to the constructor is redundant.

Parse JSON in C#

I'm trying to parse some JSON data from the Google AJAX Search API. I have this URL and I'd like to break it down so that the results are displayed. I've currently written this code, but I'm pretty lost in regards of what to do next, although there are a number of examples out there with simplified JSON strings.
Being new to C# and .NET in general I've struggled to get a genuine text output for my ASP.NET page so I've been recommended to give JSON.NET a try. Could anyone point me in the right direction to just simply writing some code that'll take in JSON from the Google AJAX Search API and print it out to the screen?
EDIT: ALL FIXED! All results are working fine. Thank you again Dreas Grech!
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ServiceModel.Web;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GoogleSearchResults g1 = new GoogleSearchResults();
const string json = #"{""responseData"": {""results"":[{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.cheese.com/"",""url"":""http://www.cheese.com/"",""visibleUrl"":""www.cheese.com"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:bkg1gwNt8u4J:www.cheese.com"",""title"":""\u003cb\u003eCHEESE\u003c/b\u003e.COM - All about \u003cb\u003echeese\u003c/b\u003e!."",""titleNoFormatting"":""CHEESE.COM - All about cheese!."",""content"":""\u003cb\u003eCheese\u003c/b\u003e - everything you want to know about it. Search \u003cb\u003echeese\u003c/b\u003e by name, by types of milk, by textures and by countries.""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://en.wikipedia.org/wiki/Cheese"",""url"":""http://en.wikipedia.org/wiki/Cheese"",""visibleUrl"":""en.wikipedia.org"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:n9icdgMlCXIJ:en.wikipedia.org"",""title"":""\u003cb\u003eCheese\u003c/b\u003e - Wikipedia, the free encyclopedia"",""titleNoFormatting"":""Cheese - Wikipedia, the free encyclopedia"",""content"":""\u003cb\u003eCheese\u003c/b\u003e is a food consisting of proteins and fat from milk, usually the milk of cows, buffalo, goats, or sheep. It is produced by coagulation of the milk \u003cb\u003e...\u003c/b\u003e""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.ilovecheese.com/"",""url"":""http://www.ilovecheese.com/"",""visibleUrl"":""www.ilovecheese.com"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:GBhRR8ytMhQJ:www.ilovecheese.com"",""title"":""I Love \u003cb\u003eCheese\u003c/b\u003e!, Homepage"",""titleNoFormatting"":""I Love Cheese!, Homepage"",""content"":""The American Dairy Association\u0026#39;s official site includes recipes and information on nutrition and storage of \u003cb\u003echeese\u003c/b\u003e.""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.gnome.org/projects/cheese/"",""url"":""http://www.gnome.org/projects/cheese/"",""visibleUrl"":""www.gnome.org"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:jvfWnVcSFeQJ:www.gnome.org"",""title"":""\u003cb\u003eCheese\u003c/b\u003e"",""titleNoFormatting"":""Cheese"",""content"":""\u003cb\u003eCheese\u003c/b\u003e uses your webcam to take photos and videos, applies fancy special effects and lets you share the fun with others. It was written as part of Google\u0026#39;s \u003cb\u003e...\u003c/b\u003e""}],""cursor"":{""pages"":[{""start"":""0"",""label"":1},{""start"":""4"",""label"":2},{""start"":""8"",""label"":3},{""start"":""12"",""label"":4},{""start"":""16"",""label"":5},{""start"":""20"",""label"":6},{""start"":""24"",""label"":7},{""start"":""28"",""label"":8}],""estimatedResultCount"":""14400000"",""currentPageIndex"":0,""moreResultsUrl"":""http://www.google.com/search?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den-GB\u0026q\u003dcheese""}}, ""responseDetails"": null, ""responseStatus"": 200}";
g1 = JSONHelper.Deserialise<GoogleSearchResults>(json);
Response.Write(g1.content);
}
}
public class JSONHelper
{
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType());
ms.Close();
return obj;
}
}
/// Deserialise from JSON
[Serializable]
public class GoogleSearchResults
{
public GoogleSearchResults() { }
public GoogleSearchResults(string _unescapedUrl, string _url, string _visibleUrl, string _cacheUrl, string _title, string _titleNoFormatting, string _content)
{
this.unescapedUrl = _unescapedUrl;
this.url = _url;
this.visibleUrl = _visibleUrl;
this.cacheUrl = _cacheUrl;
this.title = _title;
this.titleNoFormatting = _titleNoFormatting;
this.content = _content;
}
string _unescapedUrl;
string _url;
string _visibleUrl;
string _cacheUrl;
string _title;
string _titleNoFormatting;
string _content;
[DataMember]
public string unescapedUrl
{
get { return _unescapedUrl; }
set { _unescapedUrl = value; }
}
[DataMember]
public string url
{
get { return _url; }
set { _url = value; }
}
[DataMember]
public string visibleUrl
{
get { return _visibleUrl; }
set { _visibleUrl = value; }
}
[DataMember]
public string cacheUrl
{
get { return _cacheUrl; }
set { _cacheUrl = value; }
}
[DataMember]
public string title
{
get { return _title; }
set { _title = value; }
}
[DataMember]
public string titleNoFormatting
{
get { return _titleNoFormatting; }
set { _titleNoFormatting = value; }
}
[DataMember]
public string content
{
get { return _content; }
set { _content = value; }
}
}
The code currently compiles and runs perfectly, but isn't returning any results. Could someone help me with returning what I require, the results ready to print out to the screen?
Edit:
Json.NET works using the same JSON and classes as the example above.
GoogleSearchResults g1 = JsonConvert.DeserializeObject<GoogleSearchResults>(json);
Link: Serializing and Deserializing JSON with Json.NET
Related
C# - parsing json formatted data into nested hashtables
Parse JSON array
[Update]
I've just realized why you weren't receiving results back... you have a missing line in your Deserialize method. You were forgetting to assign the results to your obj :
public static T Deserialize<T>(string json)
{
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
Also, just for reference, here is the Serialize method :
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
Edit
If you want to use Json.NET here are the equivalent Serialize/Deserialize methods to the code above..
Deserialize:
JsonConvert.DeserializeObject<T>(string json);
Serialize:
JsonConvert.SerializeObject(object o);
This are already part of Json.NET so you can just call them on the JsonConvert class.
Link: Serializing and Deserializing JSON with Json.NET
Now, the reason you're getting a StackOverflow is because of your Properties.
Take for example this one :
[DataMember]
public string unescapedUrl
{
get { return unescapedUrl; } // <= this line is causing a Stack Overflow
set { this.unescapedUrl = value; }
}
Notice that in the getter, you are returning the actual property (ie the property's getter is calling itself over and over again), and thus you are creating an infinite recursion.
Properties (in 2.0) should be defined like such :
string _unescapedUrl; // <= private field
[DataMember]
public string unescapedUrl
{
get { return _unescapedUrl; }
set { _unescapedUrl = value; }
}
You have a private field and then you return the value of that field in the getter, and set the value of that field in the setter.
Btw, if you're using the 3.5 Framework, you can just do this and avoid the backing fields, and let the compiler take care of that :
public string unescapedUrl { get; set;}
I found this approach which parse JSON into a dynamic object, it extends a DynamicObject and JavascriptConverter to turn the string into an object.
DynamicJsonObject
public class DynamicJsonObject : DynamicObject
{
private IDictionary<string, object> Dictionary { get; set; }
public DynamicJsonObject(IDictionary<string, object> dictionary)
{
this.Dictionary = dictionary;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = this.Dictionary[binder.Name];
if (result is IDictionary<string, object>)
{
result = new DynamicJsonObject(result as IDictionary<string, object>);
}
else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>)
{
result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
}
else if (result is ArrayList)
{
result = new List<object>((result as ArrayList).ToArray());
}
return this.Dictionary.ContainsKey(binder.Name);
}
}
Converter
public class DynamicJsonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
if (type == typeof(object))
{
return new DynamicJsonObject(dictionary);
}
return null;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); }
}
}
Usage (sample json):
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });
dynamic glossaryEntry = jss.Deserialize(json, typeof(object)) as dynamic;
Console.WriteLine("glossaryEntry.glossary.title: " + glossaryEntry.glossary.title);
Console.WriteLine("glossaryEntry.glossary.GlossDiv.title: " + glossaryEntry.glossary.GlossDiv.title);
Console.WriteLine("glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.ID: " + glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.ID);
Console.WriteLine("glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.para: " + glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.para);
foreach (var also in glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso)
{
Console.WriteLine("glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso: " + also);
}
This method has to return true, otherwise it will throw an error. E.g. you can throw an error if a key does not exist.
Returning true and emptying result will return an empty value rather than throwing an error.
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (!this.Dictionary.ContainsKey(binder.Name))
{
result = "";
}
else
{
result = this.Dictionary[binder.Name];
}
if (result is IDictionary<string, object>)
{
result = new DynamicJsonObject(result as IDictionary<string, object>);
}
else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>)
{
result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
}
else if (result is ArrayList)
{
result = new List<object>((result as ArrayList).ToArray());
}
return true; // this.Dictionary.ContainsKey(binder.Name);
}
Your data class doesn't match the JSON object. Use this instead:
[DataContract]
public class GoogleSearchResults
{
[DataMember]
public ResponseData responseData { get; set; }
}
[DataContract]
public class ResponseData
{
[DataMember]
public IEnumerable<Results> results { get; set; }
}
[DataContract]
public class Results
{
[DataMember]
public string unescapedUrl { get; set; }
[DataMember]
public string url { get; set; }
[DataMember]
public string visibleUrl { get; set; }
[DataMember]
public string cacheUrl { get; set; }
[DataMember]
public string title { get; set; }
[DataMember]
public string titleNoFormatting { get; set; }
[DataMember]
public string content { get; set; }
}
Also, you don't have to instantiate the class to get its type for deserialization:
public static T Deserialise<T>(string json)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serialiser = new DataContractJsonSerializer(typeof(T));
return (T)serialiser.ReadObject(ms);
}
}
I just think the whole example would be useful. This is the example for this problem.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ServiceModel.Web;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Collections.Generic;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GoogleSearchResults g1 = new GoogleSearchResults();
const string json = #"{""responseData"": {""results"":[{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.cheese.com/"",""url"":""http://www.cheese.com/"",""visibleUrl"":""www.cheese.com"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:bkg1gwNt8u4J:www.cheese.com"",""title"":""\u003cb\u003eCHEESE\u003c/b\u003e.COM - All about \u003cb\u003echeese\u003c/b\u003e!."",""titleNoFormatting"":""CHEESE.COM - All about cheese!."",""content"":""\u003cb\u003eCheese\u003c/b\u003e - everything you want to know about it. Search \u003cb\u003echeese\u003c/b\u003e by name, by types of milk, by textures and by countries.""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://en.wikipedia.org/wiki/Cheese"",""url"":""http://en.wikipedia.org/wiki/Cheese"",""visibleUrl"":""en.wikipedia.org"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:n9icdgMlCXIJ:en.wikipedia.org"",""title"":""\u003cb\u003eCheese\u003c/b\u003e - Wikipedia, the free encyclopedia"",""titleNoFormatting"":""Cheese - Wikipedia, the free encyclopedia"",""content"":""\u003cb\u003eCheese\u003c/b\u003e is a food consisting of proteins and fat from milk, usually the milk of cows, buffalo, goats, or sheep. It is produced by coagulation of the milk \u003cb\u003e...\u003c/b\u003e""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.ilovecheese.com/"",""url"":""http://www.ilovecheese.com/"",""visibleUrl"":""www.ilovecheese.com"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:GBhRR8ytMhQJ:www.ilovecheese.com"",""title"":""I Love \u003cb\u003eCheese\u003c/b\u003e!, Homepage"",""titleNoFormatting"":""I Love Cheese!, Homepage"",""content"":""The American Dairy Association\u0026#39;s official site includes recipes and information on nutrition and storage of \u003cb\u003echeese\u003c/b\u003e.""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.gnome.org/projects/cheese/"",""url"":""http://www.gnome.org/projects/cheese/"",""visibleUrl"":""www.gnome.org"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:jvfWnVcSFeQJ:www.gnome.org"",""title"":""\u003cb\u003eCheese\u003c/b\u003e"",""titleNoFormatting"":""Cheese"",""content"":""\u003cb\u003eCheese\u003c/b\u003e uses your webcam to take photos and videos, applies fancy special effects and lets you share the fun with others. It was written as part of Google\u0026#39;s \u003cb\u003e...\u003c/b\u003e""}],""cursor"":{""pages"":[{""start"":""0"",""label"":1},{""start"":""4"",""label"":2},{""start"":""8"",""label"":3},{""start"":""12"",""label"":4},{""start"":""16"",""label"":5},{""start"":""20"",""label"":6},{""start"":""24"",""label"":7},{""start"":""28"",""label"":8}],""estimatedResultCount"":""14400000"",""currentPageIndex"":0,""moreResultsUrl"":""http://www.google.com/search?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den-GB\u0026q\u003dcheese""}}, ""responseDetails"": null, ""responseStatus"": 200}";
g1 = JSONHelper.Deserialise<GoogleSearchResults>(json);
foreach (Pages x in g1.responseData.cursor.pages)
{
// Anything you want to get
Response.Write(x.label);
}
}
}
public class JSONHelper
{
public static T Deserialise<T>(string json)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serialiser = new DataContractJsonSerializer(typeof(T));
return (T)serialiser.ReadObject(ms);
}
}
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
}
[DataContract]
public class GoogleSearchResults
{
[DataMember]
public ResponseData responseData { get; set; }
[DataMember]
public string responseStatus { get; set; }
}
public class ResponseData
{
[DataMember]
public Cursor cursor { get; set; }
[DataMember]
public IEnumerable<Results> results { get; set; }
}
[DataContract]
public class Cursor
{
[DataMember]
public IEnumerable<Pages> pages { get; set; }
}
[DataContract]
public class Pages
{
[DataMember]
public string start { get; set; }
[DataMember]
public string label { get; set; }
}
[DataContract]
public class Results
{
[DataMember]
public string unescapedUrl { get; set; }
[DataMember]
public string url { get; set; }
[DataMember]
public string visibleUrl { get; set; }
[DataMember]
public string cacheUrl { get; set; }
[DataMember]
public string title { get; set; }
[DataMember]
public string titleNoFormatting { get; set; }
[DataMember]
public string content { get; set; }
}
I tried to use the code above but didn't work. The JSON structure returned by Google is so different and there is a very important miss in the helper function: a call to DataContractJsonSerializer.ReadObject() that actually deserializes the JSON data into the object.
Here is the code that WORKS in 2011:
using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Collections.Generic;
namespace <YOUR_NAMESPACE>
{
public class JSONHelper
{
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType());
obj = (T)serialiser.ReadObject(ms);
ms.Close();
return obj;
}
}
public class Result
{
public string GsearchResultClass { get; set; }
public string unescapedUrl { get; set; }
public string url { get; set; }
public string visibleUrl { get; set; }
public string cacheUrl { get; set; }
public string title { get; set; }
public string titleNoFormatting { get; set; }
public string content { get; set; }
}
public class Page
{
public string start { get; set; }
public int label { get; set; }
}
public class Cursor
{
public string resultCount { get; set; }
public Page[] pages { get; set; }
public string estimatedResultCount { get; set; }
public int currentPageIndex { get; set; }
public string moreResultsUrl { get; set; }
public string searchResultTime { get; set; }
}
public class ResponseData
{
public Result[] results { get; set; }
public Cursor cursor { get; set; }
}
public class GoogleSearchResults
{
public ResponseData responseData { get; set; }
public object responseDetails { get; set; }
public int responseStatus { get; set; }
}
}
To get the content of the first result, do:
GoogleSearchResults googleResults = new GoogleSearchResults();
googleResults = JSONHelper.Deserialise<GoogleSearchResults>(jsonData);
string contentOfFirstResult = googleResults.responseData.results[0].content;
Thank you all for your help.
This is my final version, and it works thanks to your combined help !
I am only showing the changes i made, all the rest is taken from Joe Chung's work
public class GoogleSearchResults
{
[DataMember]
public ResponseData responseData { get; set; }
[DataMember]
public string responseDetails { get; set; }
[DataMember]
public int responseStatus { get; set; }
}
and
[DataContract]
public class ResponseData
{
[DataMember]
public List<Results> results { get; set; }
}
Google Map API request and parse DirectionsResponse with C#, change the json in your url to xml
and use the following code to turn the result into a usable C# Generic List Object.
Took me a while to make. But here it is
var url = String.Format("http://maps.googleapis.com/maps/api/directions/xml?...");
var result = new System.Net.WebClient().DownloadString(url);
var doc = XDocument.Load(new StringReader(result));
var DirectionsResponse = doc.Elements("DirectionsResponse").Select(l => new
{
Status = l.Elements("status").Select(q => q.Value).FirstOrDefault(),
Route = l.Descendants("route").Select(n => new
{
Summary = n.Elements("summary").Select(q => q.Value).FirstOrDefault(),
Leg = n.Elements("leg").ToList().Select(o => new
{
Step = o.Elements("step").Select(p => new
{
Travel_Mode = p.Elements("travel_mode").Select(q => q.Value).FirstOrDefault(),
Start_Location = p.Elements("start_location").Select(q => new
{
Lat = q.Elements("lat").Select(r => r.Value).FirstOrDefault(),
Lng = q.Elements("lng").Select(r => r.Value).FirstOrDefault()
}).FirstOrDefault(),
End_Location = p.Elements("end_location").Select(q => new
{
Lat = q.Elements("lat").Select(r => r.Value).FirstOrDefault(),
Lng = q.Elements("lng").Select(r => r.Value).FirstOrDefault()
}).FirstOrDefault(),
Polyline = p.Elements("polyline").Select(q => new
{
Points = q.Elements("points").Select(r => r.Value).FirstOrDefault()
}).FirstOrDefault(),
Duration = p.Elements("duration").Select(q => new
{
Value = q.Elements("value").Select(r => r.Value).FirstOrDefault(),
Text = q.Elements("text").Select(r => r.Value).FirstOrDefault(),
}).FirstOrDefault(),
Html_Instructions = p.Elements("html_instructions").Select(q => q.Value).FirstOrDefault(),
Distance = p.Elements("distance").Select(q => new
{
Value = q.Elements("value").Select(r => r.Value).FirstOrDefault(),
Text = q.Elements("text").Select(r => r.Value).FirstOrDefault(),
}).FirstOrDefault()
}).ToList(),
Duration = o.Elements("duration").Select(p => new
{
Value = p.Elements("value").Select(q => q.Value).FirstOrDefault(),
Text = p.Elements("text").Select(q => q.Value).FirstOrDefault()
}).FirstOrDefault(),
Distance = o.Elements("distance").Select(p => new
{
Value = p.Elements("value").Select(q => q.Value).FirstOrDefault(),
Text = p.Elements("text").Select(q => q.Value).FirstOrDefault()
}).FirstOrDefault(),
Start_Location = o.Elements("start_location").Select(p => new
{
Lat = p.Elements("lat").Select(q => q.Value).FirstOrDefault(),
Lng = p.Elements("lng").Select(q => q.Value).FirstOrDefault()
}).FirstOrDefault(),
End_Location = o.Elements("end_location").Select(p => new
{
Lat = p.Elements("lat").Select(q => q.Value).FirstOrDefault(),
Lng = p.Elements("lng").Select(q => q.Value).FirstOrDefault()
}).FirstOrDefault(),
Start_Address = o.Elements("start_address").Select(q => q.Value).FirstOrDefault(),
End_Address = o.Elements("end_address").Select(q => q.Value).FirstOrDefault()
}).ToList(),
Copyrights = n.Elements("copyrights").Select(q => q.Value).FirstOrDefault(),
Overview_polyline = n.Elements("overview_polyline").Select(q => new
{
Points = q.Elements("points").Select(r => r.Value).FirstOrDefault()
}).FirstOrDefault(),
Waypoint_Index = n.Elements("waypoint_index").Select(o => o.Value).ToList(),
Bounds = n.Elements("bounds").Select(q => new
{
SouthWest = q.Elements("southwest").Select(r => new
{
Lat = r.Elements("lat").Select(s => s.Value).FirstOrDefault(),
Lng = r.Elements("lng").Select(s => s.Value).FirstOrDefault()
}).FirstOrDefault(),
NorthEast = q.Elements("northeast").Select(r => new
{
Lat = r.Elements("lat").Select(s => s.Value).FirstOrDefault(),
Lng = r.Elements("lng").Select(s => s.Value).FirstOrDefault()
}).FirstOrDefault(),
}).FirstOrDefault()
}).FirstOrDefault()
}).FirstOrDefault();
I hope this will help someone.

Categories