Search Results

Search found 257 results on 11 pages for 'deserialization'.

Page 3/11 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • JSON array deserialization is crashing the Dalvik VM

    - by Sam
    I have some code grabbing a JSON array from my server and initially storing it as a string. This all works fine until I try and deserialize it using google's gson fromJson method. LogCat spits out the error: 04-08 17:46:35.163: ERROR/dalvikvm(401): Can't shrink stack: curFrame is in reserved area (0x41049000 0x410491c4) My code that causes the error is: String[] results = gson.fromJson(returnString, String[].class); Can anyone shed some light on what I am doing wrong? Cheers, Sam

    Read the article

  • Q on Python serialization/deserialization

    - by neil
    What chances do I have to instantiate, keep and serialize/deserialize to/from binary data Python classes reflecting this pattern (adopted from RFC 2246 [TLS]): enum { apple, orange } VariantTag; struct { uint16 number; opaque string<0..10>; /* variable length */ } V1; struct { uint32 number; opaque string[10]; /* fixed length */ } V2; struct { select (VariantTag) { /* value of selector is implicit */ case apple: V1; /* VariantBody, tag = apple */ case orange: V2; /* VariantBody, tag = orange */ } variant_body; /* optional label on variant */ } VariantRecord; Basically I would have to define a (variant) class VariantRecord, which varies depending on the value of VariantTag. That's not that difficult. The challenge is to find a most generic way to build a class, which serializes/deserializes to and from a byte stream... Pickle, Google protocol buffer, marshal is all not an option. I made little success with having an explicit "def serialize" in my class, but I'm not very happy with it, because it's not generic enough. I hope I could express the problem. My current solution in case VariantTag = apple would look like this, but I don't like it too much import binascii import struct class VariantRecord(object): def __init__(self, number, opaque): self.number = number self.opaque = opaque def serialize(self): out = struct.pack('>HB%ds' % len(self.opaque), self.number, len(self.opaque), self.opaque) return out v = VariantRecord(10, 'Hello') print binascii.hexlify(v.serialize()) >> 000a0548656c6c6f Regards

    Read the article

  • NetDataContractSerialization throwing deserialization error

    - by htanias
    hi, I have methods which return interface and some methods which accepts interface as parameters. I am trying to use Net DataContractSerializer but I am getting following error... The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:id. The InnerException message was 'Error in line 1 position 120. XML 'Element' 'http://tempuri.org/:id' does not contain expected attribute 'http://schemas.microsoft.com/2003/10/Serialization/:Type'. The deserializer has no knowledge of which type to deserialize. Check that the type being serialized has the same contract as the type being deserialized.'. Please see InnerException for more details. Please help me how to resolve this error.... If I use Netdatacontract attribute on Operation Contract, can i use DataContract and Datamember attribute on serializable class??? Thanks in advance...

    Read the article

  • Spring bean creation via deserialization

    - by mdma
    Spring has many different ways of creating beans, but is it possible to create a bean by deserializing a resource? My application has a number of Components, and each manipulates a certain type of data. During test, the data object is instantiated directly and set directly on the component, e.g. component.setData(someDataObject). At runtime, the data is available as a serialized object and read in from the serialized stream by the component. Rather than having each component explicitly deserialize it's data from the stream, it would be more consistent and flexible to have Spring deserialize the data object from a resource. Is there a DeserializerBeanFactory or something similar?

    Read the article

  • WCF DataContract deserialization of complex types

    - by Meidan Alon
    Hi, I have a service that returns a collection of MyClass objects. If all of the MyClass instances have null in MyClass2Reference then everything works fine. Otherwise, I get a "Connection reset" error on the client side. What am I doing wrong? Nevrmind: was a problem with NHibernate lazy proxy objects. [DataContract] public MyClass { [DataMember] int ID; [DataMember] MyClass2 MyClass2Reference; } [DataContract] public MyClass2 { [DataMember] int ID; [DataMember] string Name; }

    Read the article

  • DeSerialization doesn't work though i Implement GetObjectData method and Constructor

    - by Punit Singhi
    Hi, I have a static generic dictionary in a class. As static memeber cannot serialized so i have implented ISerializable interface and method GetObjectData to serialize. I have a constructor which will also accept SerializationInfo and StreamingContext to deserliaze the dictionay. Now when i try to serialize and deserialize , it always return 1(thoug i added 2 entries). please find the pseduo code- [Serializable] public class MyClass : ISerializable { internal static Dictionary<long, string> dict = new Dictionary<long,string>(); public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("static.dic", MyClass1.dict, typeof(Dictionary<long, string>)); } public MyClass(SerializationInfo info, StreamingContext context) { MyClass.dict= (Dictionary<long, string>)info.GetValue("static.dic", typeof(Dictionary<long, string>)); } public void Add() { dict.Add(21, "11"); } public MyClass() { dict.Add(21, "11"); } } public class MyClass { MyClass myClass = new MyClass(); public static void Main() { myClass.Add(); FileStream fileStream = new FileStream("test.binary", FileMode.Create); IFormatter bf = new BinaryFormatter(); bf.Serialize(fileStream, myClass); fileStream.Dispose(); fileStream.Close(); fileStream = new FileStream("test.binary", FileMode.Open); bf = new BinaryFormatter(); myClass = (MyClass1)bf.Deserialize(fileStream); } }

    Read the article

  • Deserialization error in a new environment

    - by cerhart
    I have a web application that calls a third-party web service. When I run it locally, I have no problems, but when I move it to my production environment, I get the following error: There is an error in XML document (2, 428). Stack: at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events) at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle) at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) at RMXClasses.RMXContactService.ContactService.getActiveSessions(String user, String pass) in C:\Users\hp\Documents\Visual Studio 2008\Projects\ReklamStore\RMXClasses\Web References\RMXContactService\Reference.cs:line 257 at I have used the same web config file from the production environment but it still works locally. My local machine is a running vista home edition and the production environment is windows server 2003. The application is written in asp.net 3.5, wierdly under the asp.net config tab in iis, 3.5 doesn't show up in the drop down list, although that version of the framework is installed. The error is not being thrown in my code, it happens during serialization. I called the method on the proxy, I have checked the arguments and they are OK. I have also logged the SOAP request and response, and they both look OK as well. I am really at a loss here. Any ideas? SOAP log: This is the soap response that the program seems to have trouble parsing only on server 2003. On my machine the soap is identical, and yet it parses with no problems. SoapResponse BeforeDeserialize; <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="urn:ContactService" xmlns:ns2="http://api.yieldmanager.com/types" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><ns1:getActiveSessionsResponse> <sessions SOAP-ENC:arrayType="ns2:session[1]" xsi:type="ns2:array_of_session"> <item xsi:type="ns2:session"> <token xsi:type="xsd:string">xxxxxxxxxxxxxxxxxxxx1ae12517584b</token> <creation_time xsi:type="xsd:dateTime">2009-09-25T05:51:19Z</creation_time> <modification_time xsi:type="xsd:dateTime">2009-09-25T05:51:19Z</modification_time> <ip_address xsi:type="xsd:string">xxxxxxxxxx</ip_address> <contact_id xsi:type="xsd:long">xxxxxx</contact_id></item></sessions> </ns1:getActiveSessionsResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>

    Read the article

  • XML Serialization and Deserialization in C#

    - by SOF User
    <job id="ID00004" name="PeakValCalcO"> <uses file="Seismogram_FFI_0_1_ID00003.grm" link="input" /> <uses file="PeakVals_FFI_0_1_ID00003.bsa" link="output" /> </job> <job id="ID00005" name="SeismogramSynthesis" > <uses file="FFI_0_1_txt.variation-s07930-h00000" link="input" /> <uses file="Seismogram_FFI_0_1_ID00005.grm" link="output" /> </job> Let say I have this XML I want to convert into .net Object how can do this i tried it but it doesn't work correct... public class jobs : List<job> { } public class job { public string id { get; set; } public string name { get; set; } public List<uses> Files { get; set; } } public class uses { public string file { get; set; } public string link { get; set; } } private void Form1_Load(object sender, EventArgs e) { XmlSerializer serializer = new XmlSerializer(typeof(jobs)); TextReader tr = new StreamReader("CyberShake_100.xml"); job b = (job)serializer.Deserialize(tr); tr.Close(); }

    Read the article

  • Python's cPickle deserialization from PHP?

    - by Ciantic
    Hi! I have to deserialize a dictionary in PHP that was serialized using cPickle in Python. In this specific case I probably could just regexp the wanted information, but is there a better way? Any extensions for PHP that would allow me to deserialize more natively the whole dictionary? Apparently it is serialized in Python like this: import cPickle as pickle data = { 'user_id' : 5 } pickled = pickle.dumps(data) print pickled Contents of such serialization cannot be pasted easily to here, because it contains binary data.

    Read the article

  • Conditional deserialization

    - by Yordan Pavlov
    I am still not sure whether the title of my question is correct and it most probably is not. However I have spent some time searching both the net and stackoverflow and I can not find a good description of the issue I am facing. Basically what I want to achieve is the ability to read some raw bytes and based on the value of some of them to interpret the rest in different ways. This is how TLV works in a way, you check the tag and depending on it - interpret the result. Of course I can always keep that logic in my C++ code, however I am looking for a solution which would move the logic out of the source code (maybe to some xml description). This would allow me to describe different encodings (protocols) more easily. I am familiar with Protocol Buffers and some other serialization libraries, however all of them solve different issue. They assume they are on both ends of the communication, while I want to describe the communication (sort of). Is such solution available, if no - why not? Are there some inherent difficulties I will face trying to implement it.

    Read the article

  • Binary serialization and deserialization without creating files (via strings)

    - by the_V
    Hi, I'm trying to create a class that will contain functions for serializing/deserializing objects to/from string. That's what it looks like now: public class BinarySerialization { public static string SerializeObject(object o) { string result = ""; if ((o.GetType().Attributes & TypeAttributes.Serializable) == TypeAttributes.Serializable) { BinaryFormatter f = new BinaryFormatter(); using (MemoryStream str = new MemoryStream()) { f.Serialize(str, o); str.Position = 0; StreamReader reader = new StreamReader(str); result = reader.ReadToEnd(); } } return result; } public static object DeserializeObject(string str) { object result = null; byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str); using (MemoryStream stream = new MemoryStream(bytes)) { BinaryFormatter bf = new BinaryFormatter(); result = bf.Deserialize(stream); } return result; } } SerializeObject method works well, but DeserializeObject does not. I always get an exception with message "End of Stream encountered before parsing was completed". What may be wrong here?

    Read the article

  • Gson Deserialize to Java Tree

    - by MountainX
    I need to deserialize some JSON to a Java tree structure that contains TreeNodes and NodeData. TreeNodes are thin wrappers around NodeData. I'll provide the JSON and the classes below. I have looked at the usual Gson help sources, including here, but I can't seem to come up with the solution. Serialization works fine with Gson. The JSON below was produced by Gson. But deserialization is the problem I need help with. Can someone show me how to write the deserializer (or suggest an alternative approach using Gson best practices)? Here is my JSON. The "data" element corresponds to class NodeData, and the "subList" JSON element corresponds to Java class TreeNode. { "data": { "version": "032", "name": "root", "path": "/", "id": "1", "parentId": "0", "toolTipText": "rootNode" }, "subList": [ { "data": { "version": "032", "name": "level1", "labelText": "Some Label Text at Level1", "path": "/root", "id": "2", "parentId": "1", "toolTipText": "a tool tip for level1" }, "subList": [ { "data": { "version": "032", "name": "level1_1", "labelText": "Label level1_1", "path": "/root/level1", "id": "3", "parentId": "2", "toolTipText": "ToolTipText for level1_1" } }, { "data": { "version": "032", "name": "level1_2", "labelText": "Label level1_2", "path": "/root/level1", "id": "4", "parentId": "2", "toolTipText": "ToolTipText for level1_2" } } ] }, { "data": { "version": "032", "name": "level2", "path": "/root", "id": "5", "parentId": "1", "toolTipText": "ToolTipText for level2" }, "subList": [ { "data": { "version": "032", "name": "level2_1", "labelText": "Label level2_1", "path": "/root/level2", "id": "6", "parentId": "5", "toolTipText": "ToolTipText for level2_1" }, "subList": [ { "data": { "version": "032", "name": "level2_1_1", "labelText": "Label level2_1_1", "path": "/root/level2/level2_1", "id": "7", "parentId": "6", "toolTipText": "ToolTipText for level2_1_1" } } ] } ] } ] } Here are the Java classes: public class Tree { private TreeNode rootElement; private HashMap<String, TreeNode> indexById; private HashMap<String, TreeNode> indexByKey; private long nextAvailableID = 0; public Tree() { indexById = new HashMap<String, TreeNode>(); indexByKey = new HashMap<String, TreeNode>(); } public long getNextAvailableID() { return this.nextAvailableID; } ... [snip] ... } public class TreeNode { private Tree tree; private NodeData data; public List<TreeNode> subList; private HashMap<String, TreeNode> indexById; private HashMap<String, TreeNode> indexByKey; //this default ctor is used only for Gson deserialization public TreeNode() { this.tree = new Tree(); indexById = tree.getIdIndex(); indexByKey = tree.getKeyIndex(); this.makeRoot(); tree.setRootElement(this); } //makes this node the root node. Calling this obviously has side effects. public NodeData makeRoot() { NodeData rootProp = new NodeData(TreeFactory.version, "example", "rootNode"); String nextAvailableID = getNextAvailableID(); if (!nextAvailableID.equals("1")) { throw new IllegalStateException(); } rootProp.setId(nextAvailableID); rootProp.setParentId("0"); rootProp.setKeyPathOnly("/"); rootProp.setSchema(tree); this.data = rootProp; rootProp.setNode(this); indexById.put(rootProp.getId(), this); indexByKey.put(rootProp.getKeyFullName(), this); return rootProp; } ... [snip] ... } public class NodeData { protected static Tree tree; private LinkedHashMap<String, String> keyValMap; protected String version; protected String name; protected String labelText; protected String path; protected String id; protected String parentId; protected TreeNode node; protected String toolTipText;//tool tip or help string protected String imagePath;//for things like images; not persisted to properties protected static final String delimiter = "/"; //this default ctor is used only for Gson deserialization public NodeData() { this("NOT_SET", "NOT_SET", "NOT_SET"); } ... [snip] ... } Side note: The tree data structure is a bit strange, as it includes indexes. Obviously, this isn't a typical search tree. In fact, the tree is used mainly to create a hierarchical path element (String) in each NodeData element. (Example: "path": "/root/level2/level2_1".) The indexes are actually used for NodeData retrieval.

    Read the article

  • How can I swap WCF deserializer from configuration

    - by JohnIdol
    I have a problem with WCF deserialization where the client hangs on the response for more than a minute. I'd like to try to swap different deserializers and see if it affects the behavior. Can I swap in/out DataContract/Xml serializers (are there any others?) from configuration, and if so can I do that with any binding, or is that out of control once the service reference is imported? Any help appreciated!

    Read the article

  • How to swap WCF deserializer from configuration

    - by JohnIdol
    I have a problem with WCF deserialization where the client hangs on the response for more than a minute. I'd like to try to swap different deserializers and see if it affects the behavior. Can I swap in/out DataContract/Xml serializers (are there any others?) from configuration, and if so can I do that with any binding? Any help appreciated!

    Read the article

  • Can I swap WCF deserializer from configuration?

    - by JohnIdol
    I have a problem with WCF deserialization where the client hangs on the response for more than a minute. I'd like to try to swap different deserializers and see if it affects the behavior. Can I swap in/out different serializers (are there any others?) from configuration, and if so can I do that with any binding, or is that out of control once the service reference is imported? Any help appreciated!

    Read the article

  • deserialize system.outofmemoryexception

    - by clanier9
    I've got a serializeable class called Cereal with several public fields shown here <Serializable> Public Class Cereal Public id As Integer Public cardType As Type Public attacker As String Public defender As String Public placedOn As String Public attack As Boolean Public placed As Boolean Public played As Boolean Public text As String Public Sub New() End Sub End Class My client computer is sending a new Cereal to the host by serializing it shown here 'sends data to host stream (c1) Private Sub cSendText(ByVal Data As String) Dim bf As New BinaryFormatter Dim c As New Cereal c.text = Data bf.Serialize(mobjClient.GetStream, c) End Sub The host listens to the stream for activity and when something gets put on it, it is supposed to deserialize it to a new Cereal shown here 'accepts data sent from the client, raised when data on host stream (c2) Private Sub DoReceive(ByVal ar As IAsyncResult) Dim intCount As Integer Try 'find how many byte is data SyncLock mobjClient.GetStream intCount = mobjClient.GetStream.EndRead(ar) End SyncLock 'if none, we are disconnected If intCount < 1 Then RaiseEvent Disconnected(Me) Exit Sub End If Dim bf As New BinaryFormatter Dim c As New Cereal c = CType(bf.Deserialize(mobjClient.GetStream), Cereal) If c.text.Length > 0 Then RaiseEvent LineReceived(Me, c.text) Else RaiseEvent CardReceived(Me, c) End If 'starts listening for action on stream again SyncLock mobjClient.GetStream mobjClient.GetStream.BeginRead(arData, 0, 1024, AddressOf DoReceive, Nothing) End SyncLock Catch e As Exception RaiseEvent Disconnected(Me) End Try End Sub when the following line executes, I get a System.OutOfMemoryException and I cannot figure out why this isn't working. c = CType(bf.Deserialize(mobjClient.GetStream), Cereal) The stream is a TCPClient stream. I'm new to serialization/deserialization and using visual studio 11

    Read the article

  • How do you deserialize a collection with child collections?

    - by Stuart Helwig
    I have a collection of custom entity objects one property of which is an ArrayList of byte arrays. The custom entity is serializable and the collection property is marked with the following attributes: [XmlArray("Images"), XmlArrayItem("Image",typeof(byte[]))] So I serialize a collection of these custom entities and pass them to a web service, as a string. The web service receives the string and byte array in tact, The following code then attempts to deserialize the collection - back into custom entities for processing... XmlSerializer ser = new XmlSerializer(typeof(List<myCustomEntity>)); StringReader reader = new StringReader(xmlStringPassedToWS); List<myCustomEntity> entities = (List<myCustomEntity>)ser.Deserialize(reader); foreach (myCustomEntity e in entities) { // ...do some stuff... foreach (myChildCollection c in entities.ChildCollection { // .. do some more stuff.... } } I've checked the XML resulting from the initial serialization and it does contain byte array - the child collection, as does the StringReader built above. After the deserialization process, the resulting collection of custom entites is fine, except that each object in the collection does not contain any items in its child collection. (i.e. it doesn't get to "...do some more stuff..." above. Can someone please explain what I am doing wrong? Is it possible to serialize ArrayLists within a generic collection of custom entities?

    Read the article

  • getting a "default" concrete class that implements an interface

    - by Roger Joys
    I am implementing a custom (and generic) Json.net serializer and hit a bump in the road that I could use some help on. When the deserializer is mapping to a property that is an interface, how can I best determine what sort of object to construct to deserialize to to place into the interface property. I have the following: [JsonConverter(typeof(MyCustomSerializer<foo>))] class foo { int Int1 { get; set; } IList<string> StringList {get; set; } } My serializer properly serializes this object, and but when it comes back in, and I try to map the json parts to to object, I have a JArray and an interface. I am currently instantiating anything enumerable like List as theList = Activator.CreateInstance(property.PropertyType); This works create to work with in the deserialization process, but when the property is IList, I get runtime complaints (obviously) about not being able to instantiate an interface. So how would I know what type of concrete class to create in a case like this? Thank you

    Read the article

  • Restore previously serialized JFrame-object, how?

    - by elementz
    Hi all. I have managed to serialize my very basic GUI-object containing a JTextArea and a few buttons to a file 'test.ser'. Now, I would like to completely restore the previously saved state from 'test.ser', but seem to have a misconception of how to properly deserialize an objects state. The class MyFrame creates the JFrame and serializes it. public class MyFrame extends JFrame implements ActionListener { // Fields JTextArea textArea; String title; static MyFrame gui = new MyFrame(); private static final long serialVersionUID = 1125762532137824262L; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub gui.run(); } // parameterless default contructor public MyFrame() { } // constructor with title public MyFrame(String title) { } // creates Frame and its Layout public void run() { JFrame frame = new JFrame(title); JPanel panel_01 = new JPanel(); JPanel panel_02 = new JPanel(); JTextArea textArea = new JTextArea(20, 22); textArea.setLineWrap(true); JScrollPane scrollPane = new JScrollPane(textArea); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); panel_01.add(scrollPane); // Buttons JButton saveButton = new JButton("Save"); saveButton.addActionListener(this); JButton loadButton = new JButton("Load"); loadButton.addActionListener(this); panel_02.add(loadButton); panel_02.add(saveButton); // Layout frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(BorderLayout.CENTER, panel_01); frame.getContentPane().add(BorderLayout.SOUTH, panel_02); frame.setSize(300, 400); frame.setVisible(true); } /* * */ public void serialize() { try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test.ser")); oos.writeObject(gui); oos.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } public void actionPerformed(ActionEvent ev) { System.out.println("Action received!"); gui.serialize(); } } Here I try to do the deserialization: public class Deserialize { static Deserialize ds; static MyFrame frame; public static void main(String[] args) { try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.ser")); frame = (MyFrame) ois.readObject(); ois.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Maybe somebody could point me into the direction where my misconception is? Thx in advance!

    Read the article

  • Iterate through deserialized xml object

    - by Bruce Adams
    I have a deserialized xml c# objet. I need to iterate through the oject to display all items, in this case there's just one, and display the name, colors and sizes for each item. The xml: <?xml version="1.0" encoding="utf-8"?> <Catalog Name="Example"> <Items> <Item Name="ExampleItem"> <Colors> <Color Name="Black" Value="#000" /> <Color Name="White" Value="#FFF" /> </Colors> <Sizes> <Size Name="Small" Value="10" /> <Size Name="Medium" Value="20" /> </Sizes> </Item> </Items> </Catalog> xsd.exe generated classes: //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.4927 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System.Xml.Serialization; // // This source code was auto-generated by xsd, Version=2.0.50727.42. // /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)] [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)] public partial class Catalog { private CatalogItemsItem[][] itemsField; private string nameField; /// <remarks/> [System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] [System.Xml.Serialization.XmlArrayItemAttribute("Item", typeof(CatalogItemsItem[]), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] public CatalogItemsItem[][] Items { get { return this.itemsField; } set { this.itemsField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Name { get { return this.nameField; } set { this.nameField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)] public partial class CatalogItemsItem { private CatalogItemsItemColorsColor[][] colorsField; private CatalogItemsItemSizesSize[][] sizesField; private string nameField; /// <remarks/> [System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] [System.Xml.Serialization.XmlArrayItemAttribute("Color", typeof(CatalogItemsItemColorsColor[]), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] public CatalogItemsItemColorsColor[][] Colors { get { return this.colorsField; } set { this.colorsField = value; } } /// <remarks/> [System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] [System.Xml.Serialization.XmlArrayItemAttribute("Size", typeof(CatalogItemsItemSizesSize[]), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] public CatalogItemsItemSizesSize[][] Sizes { get { return this.sizesField; } set { this.sizesField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Name { get { return this.nameField; } set { this.nameField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)] public partial class CatalogItemsItemColorsColor { private string nameField; private string valueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Name { get { return this.nameField; } set { this.nameField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Value { get { return this.valueField; } set { this.valueField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)] public partial class CatalogItemsItemSizesSize { private string nameField; private string valueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Name { get { return this.nameField; } set { this.nameField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string Value { get { return this.valueField; } set { this.valueField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)] [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)] public partial class NewDataSet { private Catalog[] itemsField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("Catalog")] public Catalog[] Items { get { return this.itemsField; } set { this.itemsField = value; } } } Deserialization code: System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(typeof(Catalog)); TextReader reader = new StreamReader("catalog.xml"); Catalog catalog = (Catalog)xSerializer.Deserialize(reader); foreach (var item in catalog.Items) { } reader.Close(); When I setp through the code there is one item present in catalog.items, but it is empty, no name, colors or sizes. Any ideas what I need to do? Thanks

    Read the article

  • Why is my WCF RIA Services custom object deserializing with an extra list member?

    - by oasasaurus
    I have been developing a Silverlight WCF RIA Services application dealing with mock financial transactions. To more efficiently send summary data to the client without going overboard with serialized entities I have created a summary class that isn’t in my EDM, and figured out how to serialize and send it over the wire to the SL client using DataContract() and DataMember(). Everything seemed to be working out great, until I tried to bind controls to a list inside my custom object. The list seems to always get deserialized with an extra, almost empty entity in it that I don’t know how to get rid of. So, here are some of the pieces. First the relevant bits from the custom object class: <DataContract()> _ Public Class EconomicsSummary Public Sub New() RecentTransactions = New List(Of Transaction) TotalAccountHistory = New List(Of Transaction) End Sub Public Sub New(ByVal enUser As EntityUser) Me.UserId = enUser.UserId Me.UserName = enUser.UserName Me.Accounts = enUser.Accounts Me.Jobs = enUser.Jobs RecentTransactions = New List(Of Transaction) TotalAccountHistory = New List(Of Transaction) End Sub <DataMember()> _ <Key()> _ Public Property UserId As System.Guid <DataMember()> _ Public Property NumTransactions As Integer <DataMember()> _ <Include()> _ <Association("Summary_RecentTransactions", "UserId", "User_UserId")> _ Public Property RecentTransactions As List(Of Transaction) <DataMember()> _ <Include()> _ <Association("Summary_TotalAccountHistory", "UserId", "User_UserId")> _ Public Property TotalAccountHistory As List(Of Transaction) End Class Next, the relevant parts of the function called to return the object: Public Function GetEconomicsSummary(ByVal guidUserId As System.Guid) As EconomicsSummary Dim objOutput As New EconomicsSummary(enUser) For Each objTransaction As Transaction In (From t As Transaction In Me.ObjectContext.Transactions.Include("Account") Where t.Account.aspnet_User_UserId = guidUserId Select t Order By t.TransactionDate Descending Take 10) objTransaction.User_UserId = objOutput.UserId objOutput.RecentTransactions.Add(objTransaction) Next objOutput.NumTransactions = objOutput.RecentTransactions.Count … Return objOutput End Function Notice that I’m collecting the NumTransactions count before serialization. Should be 10 right? It is – BEFORE serialization. The DataGrid is bound to the data source as follows: <sdk:DataGrid AutoGenerateColumns="False" Height="100" MaxWidth="{Binding ElementName=aciSummary, Path=ActualWidth}" ItemsSource="{Binding Source={StaticResource EconomicsSummaryRecentTransactionsViewSource}, Mode=OneWay}" Name="gridRecentTransactions" RowDetailsVisibilityMode="VisibleWhenSelected" IsReadOnly="True"> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn x:Name="TransactionDateColumn" Binding="{Binding Path=TransactionDate, StringFormat=\{0:d\}}" Header="Date" Width="SizeToHeader" /> <sdk:DataGridTextColumn x:Name="AccountNameColumn" Binding="{Binding Path=Account.Title}" Header="Account" Width="SizeToCells" /> <sdk:DataGridTextColumn x:Name="CurrencyAmountColumn" Binding="{Binding Path=CurrencyAmount, StringFormat=\{0:c\}}" Header="Amount" Width="SizeToHeader" /> <sdk:DataGridTextColumn x:Name="TitleColumn" Binding="{Binding Path=Title}" Header="Description" Width="SizeToCells" /> <sdk:DataGridTextColumn x:Name="ItemQuantityColumn" Binding="{Binding Path=ItemQuantity}" Header="Qty" Width="SizeToHeader" /> </sdk:DataGrid.Columns> </sdk:DataGrid> You might be wondering where the ItemsSource is coming from, that looks like this: <CollectionViewSource x:Key="EconomicsSummaryRecentTransactionsViewSource" Source="{Binding Path=DataView.RecentTransactions, ElementName=EconomicsSummaryDomainDataSource}" /> When I noticed that the DataGrid had the extra row I tried outputting some data after the data source finishes loading, as follows: Private Sub EconomicsSummaryDomainDataSource_LoadedData(ByVal sender As System.Object, ByVal e As System.Windows.Controls.LoadedDataEventArgs) Handles EconomicsSummaryDomainDataSource.LoadedData If e.HasError Then System.Windows.MessageBox.Show(e.Error.ToString, "Load Error", System.Windows.MessageBoxButton.OK) e.MarkErrorAsHandled() End If Dim objSummary As EconomicsSummary = CType(EconomicsSummaryDomainDataSource.Data(0), EconomicsSummary) Dim sb As New StringBuilder("") sb.AppendLine(String.Format("Num Transactions: {0} ({1})", objSummary.RecentTransactions.Count.ToString(), objSummary.NumTransactions.ToString())) For Each objTransaction As Transaction In objSummary.RecentTransactions sb.AppendLine(String.Format("Recent TransactionId {0} dated {1} CurrencyAmount {2} NewBalance {3}", objTransaction.TransactionId.ToString, objTransaction.TransactionDate.ToString("d"), objTransaction.CurrencyAmount.ToString("c"), objTransaction.NewBalance.ToString("c"))) Next txtDebug.Text = sb.ToString() End Sub Output from that looks like this: Num Transactions: 11 (10) Recent TransactionId 2283 dated 6/1/2010 CurrencyAmount $31.00 NewBalance $392.00 Recent TransactionId 2281 dated 5/31/2010 CurrencyAmount $33.00 NewBalance $361.00 Recent TransactionId 2279 dated 5/28/2010 CurrencyAmount $8.00 NewBalance $328.00 Recent TransactionId 2277 dated 5/26/2010 CurrencyAmount $22.00 NewBalance $320.00 Recent TransactionId 2275 dated 5/24/2010 CurrencyAmount $5.00 NewBalance $298.00 Recent TransactionId 2273 dated 5/21/2010 CurrencyAmount $19.00 NewBalance $293.00 Recent TransactionId 2271 dated 5/20/2010 CurrencyAmount $20.00 NewBalance $274.00 Recent TransactionId 2269 dated 5/19/2010 CurrencyAmount $48.00 NewBalance $254.00 Recent TransactionId 2267 dated 5/18/2010 CurrencyAmount $42.00 NewBalance $206.00 Recent TransactionId 2265 dated 5/14/2010 CurrencyAmount $5.00 NewBalance $164.00 Recent TransactionId 0 dated 6/1/2010 CurrencyAmount $0.00 NewBalance $361.00 So I have a few different questions: -First and foremost, where the devil is that extra Transaction entity coming from and how do I get rid of it? Does it have anything to do with the other list of Transaction entities being serialized as part of the EconomicsSummary class (TotalAccountHistory)? Do I need to decorate the EconomicsSummary class members a little more/differently? -Second, where are the peculiar values coming from on that extra entity? PRE-POSTING UPDATE 1: I did a little checking, it looks like that last entry is the first one in the TotalAccountHistory list. Do I need to do something with CollectionDataContract()? PRE-POSTING UPDATE 2: I fixed one bug in TotalAccountHistory, since the objects weren’t coming from the database their keys weren’t unique. So I set the keys on the Transaction entities inside TotalAccountHistory to be unique and guess what? Now, after deserialization RecentTransactions contains all its original items, plus every item in TotalAccountHistory. I’m pretty sure this has to do with the deserializer getting confused by two collections of the same type. But I don’t yet know how to resolve it…

    Read the article

  • JavaScriptSerializer deserialize object "collection" as property in object failing

    - by bill
    Hi All, I have a js object structured like: object.property1 = "some string"; object.property2 = "some string"; object.property3.property1 = "some string"; object.property3.property2 = "some string"; object.property3.property2 = "some string"; i'm using JSON.stringify(object) to pass this with ajax request. When i try to deserialize this using JavaScriptSerializer.Deserialize as a Dictionary i get the following error: No parameterless constructor defined for type of 'System.String'. This exact same process is working for regular object with non "collection" properties.. thanks for any help!

    Read the article

  • Deserializing JSON into an object with Json.NET

    - by hmemcpy
    Hello. I'm playing a little bit with the new StackOverflow API. Unfortunately, my JSON is a bit weak, so I need some help. I'm trying to deserialize this JSON of a User: {"user":{ "user_id": 1, "user_type": "moderator", "creation_date": 1217514151, "display_name": "Jeff Atwood", ... "accept_rate": 100 }} into an object which I've decorated with JsonProperty attributes: [JsonObject(MemberSerialization.OptIn)] public class User { [JsonProperty("user_id", Required = Required.Always)] public virtual long UserId { get; set; } [JsonProperty("display_name", Required = Required.Always)] public virtual string Name { get; set; } ... } I get the following exception: Newtonsoft.Json.JsonSerializationException: Required property 'user_id' not found in JSON. Is this because the JSON object is an array? If so, how can I deserialize it to the one User object? Thanks in advance!

    Read the article

  • DataContractSerializer does not properly deserialize, values for methods in object are missing

    - by sachin
    My SomeClass [Serializable] [DataContract(Namespace = "")] public class SomeClass { [DataMember] public string FirstName { get; set; } [DataMember] public string LastName { get; set; } [DataMember] private IDictionary<long, string> customValues; public IDictionary<long, string> CustomValues { get { return customValues; } set { customValues = value; } } } My XML File: <?xml version="1.0" encoding="UTF-8"?> <SomeClass> <FirstName>John</FirstName> <LastName>Smith</LastName> <CustomValues> <Value1>One</Value1> <Value2>Two</Value2> </CustomValues > </SomeClass> But my problem is for the class, i am only getting some of the data for my methods when i deserialize. var xmlRoot = XElement.Load(new StreamReader( filterContext.HttpContext.Request.InputStream, filterContext.HttpContext.Request.ContentEncoding)); XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(xmlRoot.CreateReader()); DataContractSerializer ser = new DataContractSerializer(typeof(SomeClass)); //Deserialize the data and read it from the instance. SomeClass someClass = (SomeClass)ser.ReadObject(reader, true); So when I check "someClass", FirstName will have the value john, But the LastName will be null. Mystery is how can i get some of the data and not all of the data for the class. So DataContractSerializer is not pulling up all the data from xml when deserializing. Am i doing something wrong. Any help is appreciated. Thanks in advance. Let me know if anyone has the same problem or any one has solution

    Read the article

  • String to Date/Time

    - by theblip
    I have a serialized DateTime string which looks like this: 2010-04-14T16:32:06.75+10:00 What is the simplest way of deserializing/parsing it back into a DateTime?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >