Search Results

Search found 468 results on 19 pages for 'deserialize'.

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

  • What happens if we serialize and deserialize two objects which references to each other?

    - by Seregwethrin
    To make it more clear, this is a quick example: class A implements Serializable { public B b; } class B implements Serializable { public A a; } A a = new A(); B b = new B(); a.b = b; b.a = a; So what happens if we serialize a and b objects into a file and deserialize from that file? I thought we get 4 objects, 2 of each. Identical objects but different instances. But I'm not sure if there's anything else or is it right or wrong. If any technology needed to answer, please think based on Java. Thank you.

    Read the article

  • Is this a good way to generically deserialize objects?

    - by Damien Wildfire
    I have a stream onto which serialized objects representing messages are dumped periodically. The objects are one of a very limited number of types, and other than the actual sequence of bytes that arrives, I have no way of knowing what type of message it is. I would like to simply try to deserialize it as an object of a particular type, and if an exception is thrown, try again with the next type. I have an interface that looks like this: public interface IMessageHandler<T> where T : class, IMessage { T Handle(string message); } // elsewhere: // (These are all xsd.exe-generated classes from an XML schema.) public class AppleMessage : IMessage { ... } public class BananaMessage : IMessage { ... } public class CoconutMessage : IMessage { ... } Then I wrote a GenericHandler<T> that looks like this: public class GenericHandler<T> : IMessageHandler<T> where T: class, IMessage { public class MessageHandler : IMessageHandler { T IMessageHandler.Handle(string message) { T result = default(T); try { // This utility method tries to deserialize the object with an // XmlSerializer as if it were an object of type T. result = Utils.SerializationHelper.Deserialize<T>(message); } catch (InvalidCastException e) { result = default(T); } return result; } } } Two questions: Using my GenericHandler<T> (or something similar to it), I'd now like to populate a collection with handlers that each handle a different type. Then I want to invoke each handler's Handle method on a particular message to see if it can be deserialized. If I get a null result, move onto the next handler; otherwise, the message has been deserialized. Can this be done? Is there a better way to deserialize data of unknown (but restricted) type?

    Read the article

  • How to deserialize null array to null in c#?

    - by Aen Sidhe
    Here is my class: public class Command { [XmlArray(IsNullable = true)] public List<Parameter> To { get; set; } } When I serialize an object of this class: var s = new XmlSerializer(typeof(Command)); s.Serialize(Console.Out, new Command()); it prints as expected (xml header and default MS namespaces are omitted): <Command><To xsi:nil="true" /></Command> When I took this xml and tried to deserialize it I got stucked, because it always print "Not null": var t = s.Deserialize(...); if (t.To == null) Console.WriteLine("Null"); else Console.WriteLine("Not null"); How to force deserializer to make my list null, if it is null in xml?

    Read the article

  • How to deserialize from json to ActiveRecord objects with associations?

    - by Carmine Paolino
    In my Rails application there is a model that has some has_one associations (this is a fabricated example): class Person::Admin < ActiveRecord::Base has_one :person_monthly_revenue has_one :dude_monthly_niceness accepts_nested_attributes_for :person_monthly_revenue, :dude_monthly_niceness end class Person::MonthlyRevenue < ActiveRecord::Base belongs_to :person_admin end class Dude::MonthlyNiceness < ActiveRecord::Base belongs_to :person_admin end The application talks to a backend that computes some data and returns a piece of JSON like this: { "dude_monthly_niceness": { "february": 1.1153232569518972, "october": 1.1250217200558268, "march": 1.3965786869658541, "august": 1.6293418014601631, "september": 1.4062771500697835, "may": 1.7166279693955291, "january": 1.0086401628086725, "june": 1.5711510228365859, "april": 1.5614525597326563, "december": 0.99894169970474289, "july": 1.7263264324994585, "november": 0.95044938418509506 }, "person_monthly_revenue": { "february": 10.585596551505297, "october": 10.574823016656749, "march": 9.9125274764852787, "august": 9.2111604702328922, "september": 9.7905249446675153, "may": 9.1329712474607962, "january": 10.479614016604238, "june": 9.3710235926961936, "april": 9.5897372624830304, "december": 10.052587677671438, "july": 8.9508877843925561, "november": 10.925339756096172 }, } To deserialize it, I use ActiveRecord's from_json, but instead of a Person::Admin object with all the associations in place, I get this error: >> Person::Admin.new.from_json(json) NameError: uninitialized constant Person::Admin::DudeMonthlyNiceness Am I doing something wrong? Is there a better way to deserialize data? (I can modify the backend easily)

    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

  • Deserialize JSON, sometimes value is an array, sometimes "" (blank string).

    - by karl.r
    I am trying to deserialize a field: "presenters":[{...},{...}] but some of the rows come back with only: "presenters":"" When the serializer gets to the row with that empty string I get: Error converting value "" to type 'System.Collections.Generic.List`1[DataPrototype.Model.Presenter]'. Am I right in thinking that I need a JsonConverter that will change the empty string into an empty List?

    Read the article

  • How to send a XmlSerializer Class to a WebService and then Deserialize it?

    - by pee2002
    Hi! I want to be able to send a XmlSerializer class (which is generated obvious in remote C# application) over a WebService that will then deserialize it into a class. (I didnt know it its possible either) My class is: SystemInfo I'm serializing it this way: XmlSerializer mySerializer = new XmlSerializer(typeof(SystemInfo)); StreamWriter myWriter = new StreamWriter(textBox1.Text); mySerializer.Serialize(myWriter, sysinfo); How can i build the WebService? [WebMethod] public void Reports(XmlSerializer xmlSerializer) { . . . } Can anyone help me out? Regards

    Read the article

  • OutOfMemoryError calling XmlSerializer.Deserialize() - not related to XML size!

    - by Mike Atlas
    This is a really crazy bug. The following is throwing an OutOfMemoryException, for XML snippits that are very short (e.g., <ABC def='123'/>) of one type, but not for others of the same size but a different type: (e.g., <ZYX qpr='baz'/>). public static T DeserializeXmlNode<T>(XmlNode node) { try { return (T)new XmlSerializer(typeof(T)) .Deserialize(new XmlNodeReader(node)); } catch (Exception ex) { throw; // just for catching a breakpoint. } } I read in this MSDN article that if I were using XmlSerializer with additional parameters in the constructor, I'd end up generating un-cached serializer assemblies every it got called, causing an Assembly Leak. But I'm not using additional parameters in the constructor. It also happens on the first call, too, so the AppDomain is fresh. Worse yet, it is only thrown in release builds, not debug builds. What gives?

    Read the article

  • How to deserialize JSON text into a date type using Windows 8 JSON.parse?

    - by canderso
    I'm building a Windows 8 Metro app (aka "Modern UI Style" or "Windows Store app") in HTML5/JavaScript consuming JSON Web Services and I'm bumping into the following issue: in which format should my JSON Web Services serialize dates for the Windows 8 Metro JSON.parse method to deserialize those in a date type? I tried: sending dates using the ISO-8601 format, (JSON.parse returns a string), sending dates such as "/Date(1198908717056)/" as explained here (same result). I'm starting to doubt that Windows 8's JSON.parse method supports dates as even when parsing the output of its own JSON.stringify method does not return a date type. Example: var d = new Date(); // => a new date var str = JSON.stringify(d); // str is a string => "\"2012-07-10T14:44:00.000Z\"" var date2 = JSON.parse(str); // date2 is a string => "2012-07-10T14:44:00.000Z"

    Read the article

  • Can JAXB store the class name in the XML so that the the deserialize code doesn't need knowledge of the class?

    - by Andrew
    It seems the standard approach for deserializing JAXB XML is to specify the package name when creating the context. Then, JAXB looks up the class based on the root element: JAXBContext jc = JAXBContext.newInstance("com.foo"); Unmarshaller u = jc.createUnmarshaller(); Object o = u.unmarshal(new StringReader("...")); I'm looking for a more flexible approach where I don't have to specify the package name and could still deserialize any object. This would be as simple as JAXB storing the package in the XML, but I can't seem to find out how to do this. I can write the code to do it myself but that would be unpleasant. It would like JAXB to do it, if possible. BTW, I am not using schemas, just Annotations and marshal/unmarshal. Any ideas?

    Read the article

  • How do I serialize/deserialize a NHibernate entity that has references to other objects?

    - by Daniel T.
    I have two NHibernate-managed entities that have a bi-directional one-to-many relationship: public class Storage { public virtual string Name { get; set; } public virtual IList<Box> Boxes { get; set; } } public class Box { public virtual string Box { get; set; } [DoNotSerialize] public virtual Storage ParentStorage { get; set; } } A Storage can contain many Boxes, and a Box always belongs in a Storage. I want to edit a Box's name, so I send it to the client using JSON. Note that I don't serialize ParentStorage because I'm not changing which storage it's in. The client edits the name and sends the Box back as JSON. The server deserializes it back into a Box entity. Problem is, the ParentStorage property is null. When I try to save the Box to the database, it updates the name, but also removes the relationship to the Storage. How do I properly serialize and deserialize an entity like a Box, while keeping the JSON data size to a minimum?

    Read the article

  • How do I deserialize a namespaced element to an object in .net?

    - by pc1oad1etter
    Given this XML snippet: ... <InSide:setHierarchyUpdates> <automaticUpdateInterval>5</automaticUpdateInterval> <shouldRunAutomaticUpdates>true<shouldRunAutomaticUpdates> </InSide:setHierarchyUpdates> ... I am attempting to serialize this object: Imports System.Xml.Serialization <XmlRoot(ElementName:="setHierarchyUpdates", namespace:="InSide")> _ Public Class HierarchyUpdate <XmlElement(ElementName:="shouldRunAutomaticUpdates")> _ Public shouldRunAutomaticUpdates As Boolean <XmlElement(ElementName:="automaticUpdateInterval")> _ Public automaticUpdateInterval As Integer End Class Like this: Dim hierarchyUpdater As New HierarchyUpdate Dim x As New XmlSerializer(hierarchyUpdater.GetType) Dim objReader As Xml.XmlNodeReader = New Xml.XmlNodeReader(myXMLNode) hierarchyUpdater = x.Deserialize(objReader) However, the object, after deserialization, has values of false and zero. If I switch the objReader to a streamreader and read this in as a file, with none of its parents and no namespaces, it works: <setHierarchyUpdates> <automaticUpdateInterval>5</automaticUpdateInterval> <shouldRunAutomaticUpdates>true<shouldRunAutomaticUpdates> </setHierarchyUpdates> What am I doing wrong? Should I use something other than XMLRoot in the class definition, because, as an XML node, it's not really the root? If so, what? Why are no errors returned when this fails?

    Read the article

  • WCF fails to deserialize correct(?) response message security headers (Security header is empty)

    - by Soeteman
    I'm communicating with an OC4J webservice, using a WCF client. The client is configured as follows: <basicHttpBinding> <binding name="MyBinding"> <security mode="TransportWithMessageCredential"> <transport clientCredentialType="None" proxyCredentialType="None" realm=""/> <message clientCredentialType="UserName" algorithmSuite="Default"/> </security> </binding> My clientcode looks as follows: ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy(); string username = ConfigurationManager.AppSettings["user"]; string password = ConfigurationManager.AppSettings["pass"]; // client instance maken WebserviceClient client = new WebserviceClient(); client.Endpoint.Binding = new BasicHttpBinding("MyBinding"); // credentials toevoegen client.ClientCredentials.UserName.UserName = username; client.ClientCredentials.UserName.Password = password; //uitvoeren request var response = client.Ping(); I've altered the CertificatePolicy to accept all certificates, because I need to insert Charles (ssl proxy) in between client and server to intercept the actual Xml that is sent across te wire. My request looks as follows: <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"> <s:Header> <o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> <u:Timestamp u:Id="_0"> <u:Created>2010-04-01T09:47:01.161Z</u:Created> <u:Expires>2010-04-01T09:52:01.161Z</u:Expires> </u:Timestamp> <o:UsernameToken u:Id="uuid-9b39760f-d504-4e53-908d-6125a1827aea-21"> <o:Username>user</o:Username> <o:Password o:Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username- token-profile-1.0#PasswordText">pass</o:Password> </o:UsernameToken> </o:Security> </s:Header> <s:Body> <getPrdStatus xmlns="http://mynamespace.org/wsdl"> <request xmlns="" xmlns:a="http://mynamespace.org/wsdl" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <a:IsgrStsRequestTypeUser> <a:prdCode>LEPTO</a:prdCode> <a:sequenceNumber i:nil="true" /> <a:productionType i:nil="true" /> <a:statusDate>2010-04-01T11:47:01.1617641+02:00</a:statusDate> <a:ubn>123456</a:ubn> <a:animalSpeciesCode>RU</a:animalSpeciesCode> </a:IsgrStsRequestTypeUser> </request> </getPrdStatus> </s:Body> </s:Envelope> In return, I receive the following response: <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns0="http://mynamespace.org/wsdl"> <env:Header> <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" env:mustUnderstand="1" /> </env:Header> <env:Body> <ns0:getPrdStatusResponse> <result> <ns0:IsgrStsResponseTypeUser> <ns0:prdCode>LEPTO</ns0:prdCode> <ns0:color>green</ns0:color> <ns0:stsCode>LEP1</ns0:stsCode> <ns0:sequenceNumber xsi:nil="1" /> <ns0:productionType xsi:nil="1" /> <ns0:IAndRCode>00</ns0:IAndRCode> <ns0:statusDate>2010-04-01T00:00:00.000+02:00</ns0:statusDate> <ns0:description>Gecertificeerd vrij</ns0:description> <ns0:ubn>123456</ns0:ubn> <ns0:animalSpeciesCode>RU</ns0:animalSpeciesCode> <ns0:name>gecertificeerd vrij</ns0:name> <ns0:ranking>17</ns0:ranking> </ns0:IsgrStsResponseTypeUser> </result> </ns0:getPrdStatusResponse> </env:Body> </env:Envelope> Why can't WCF deserialize this response header? I'm getting a "Security header is empty" exception: Server stack trace: at System.ServiceModel.Security.ReceiveSecurityHeader.Process(TimeSpan timeout) at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessageCore(Message& message, TimeSpan timeout) at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout) at System.ServiceModel.Security.SecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates) at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout) at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout) at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Who knows what is going on here? I've already tried Rick Strahl's suggestion and removed the timestamp from the request header. Any help greatly appreciated!

    Read the article

  • How do i deserialize an object with pyYaml using safe_load?

    - by systempuntoout
    Having a snippet like this: import yaml class User(object): def __init__(self, name, surname): self.name= name self.surname= surname user = User('spam', 'eggs') serialized_user = yaml.dump(user) deserialized_user = yaml.load(serialized_user) print "name: %s, surname %s" % (deserialized_user.name, deserialized_user.surname) Yaml docs says that it is not safe to call yaml.load with any data received from an untrusted source; so, what do i need to modify to my snippet\class to use safe_load method? Is it possible?

    Read the article

  • How to deserialize an object with pyYaml using safe_load?

    - by systempuntoout
    Having a snippet like this: import yaml class User(object): def __init__(self, name, surname): self.name= name self.surname= surname user = User('spam', 'eggs') serialized_user = yaml.dump(user) #Network deserialized_user = yaml.load(serialized_user) print "name: %s, sname: %s" % (deserialized_user.name, deserialized_user.surname) Yaml docs says that it is not safe to call yaml.load with any data received from an untrusted source; so, what do i need to modify to my snippet\class to use safe_load method? Is it possible?

    Read the article

  • Using XStream to deserialize an XML response with separate "success" and "failure" forms?

    - by Chris Markle
    I am planning on using XStream with Java to convert between objects and XML requests and XML responses and objects, where the XML is flowing over HTTP/HTTPS. On the response side, I can get a "successful" response, which seems like it would map to one Java class, or a "failure" response, which seems like it would map to another Java class. For example, for a "file list" request, I could get an affirmative response e.g., <?xml version="1.0" encoding="UTF-8"?> <response> <success>true</success> <files> <file>[...]</file> <file>[...]</file> <file>[...]</file> </files> </response> or I could get a negative response e.g., <?xml version="1.0" encoding="UTF-8"?> <response> <success>false</success> <error> <errorCode>-502</errorCode> <systemMessage>[...]AuthenticationException</systemMessage> <userMessage>Not authenticated</userMessage> </error> </response> To handle this, should I include fields in one class for both cases or should I somehow use XStream to "conditionally" create one of the two potential classes? The case with fields from both response cases in the same object would look something like this: Class Response { boolean success; ArrayList<File> files; ResponseError error; [...] } Class File { String name; long size; [...] } Class ResponseError { int errorCode; String systemMessage; String userMessage; [...] } I don't know what the "use XStream and create different objects in case of success or error" looks like. Is it possible to do that somehow? Is it better or worse way to go? Anyway, any advice on how to handle using XStream to deal with this success vs. failure response case would be appreciated. Thanks in advance!

    Read the article

  • What is the best way to deserialize generics written with a different version of a signed assembly?

    - by Rick Minerich
    In other cases it has been suggested that you simply add a SerializationBinder which removes the version from the assembly type. However, when using generic collections of a type found in a signed assembly, that type is strictly versioned based on its assembly. Here is what I've found works. internal class WeaklyNamedAssemblyBinder : SerializationBinder { public override Type BindToType(string assemblyName, string typeName) { ResolveEventHandler handler = new ResolveEventHandler(CurrentDomain_AssemblyResolve); AppDomain.CurrentDomain.AssemblyResolve += handler; Type returnedType; try { AssemblyName asmName = new AssemblyName(assemblyName); var assembly = Assembly.Load(asmName); returnedType = assembly.GetType(typeName); } catch { returnedType = null; } finally { AppDomain.CurrentDomain.AssemblyResolve -= handler; } return returnedType; } Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { string truncatedAssemblyName = args.Name.Split(',')[0]; Assembly assembly = Assembly.Load(truncatedAssemblyName); return assembly; } } However, causing the binding process to change globally seems rather dangerous to me. Strange things could happen if serialization was happening in multiple threads. Perhaps a better solution is to do some regex manipulation of the typeName? What do you think?

    Read the article

  • how to use a generated dbml classes to deserialize xml via linq?

    - by Eelco Meuter
    Hi, I have a complex data structure, which I boiled down in a dbml file with one class and 6 one-to-many relations. This data must also be read via xml. The xml structure is something like: <table id=1> <column 1></column 1> <column n></column n> <m-n table x> <column 1></column 1> </m-n table x> </table> where the tag <m-n table x> is one of the six related tables. The idea is to generate an xsd based upon the dbml, which I can use to create and validate a xml. This xml can hopefully deserialized into the dbml classes. The question is: Can this be done? If so, how do I generate the xsd. I use a sql server express 2008 r2 as backend. Thanks in advance for your time!

    Read the article

  • How to "serialize" and "deserialize" command line arguments to string in bash?

    - by Vi
    I call my script: $ ./script 'a!#*`*& ^$' "sdf sdf\"qw sdsdf" 1 -- 2 3 It gets arguments: 1: a!#*`*& ^$ 2: sdf sdf"qw sdsdf 3: 1 4: -- 5: 2 6: 3 If I need to call something with the same arguments locally, I do this: someprogram "$@" But how can I put all that array to a string (to store in file or in environment variable or pass over TCP eaisly) and then turn it back to command line arguments somewhere? I want it to be simple, short and secure. export CMDLINE="$@" # What is in CMDLINE now? Escaped or not? sh -c "someprogram $CMDLINE" # Will it do what I mean? Ideally I want two bash subroutines: the first turns turns any Bash array into a [a-zA-Z0-9_]* string, the other turns it back to Bash array I can use.

    Read the article

  • Is there a way to deserialize an object into "$this"?

    - by Andreas Bonini
    I'm writing a class to handle a memcached object. The idea was to create abstract class Cachable and all the cachable objects (such as User, Post, etc) would be subclasses of said class. The class offers some method such as Load() which calls the abstract function LoadFromDB() if the object is not cached, functions to refresh/invalidate the cache, etc. The main problem is in Load(); I wanted to do something similar: protected function Load($id) { $this->memcacheId = $id; $this->Connect(); $cached = $this->memcache->get(get_class($this) . ':' . $id); if($cached === false) { $this->SetLoaded(LoadFromDB($id)); UpdateCache(); } else { $this = $cached; $this->SetLoaded(true); } } Unfortunately I need $this to become $cached (the cached object); is there any way to do that? Was the "every cachable object derives from the cachable class" a bad design idea?

    Read the article

  • How to deserialize an html div when it has certain attributes to it?

    - by user1676874
    For example this: <div class="link_text"> <a href="http://www.stackoverflow.com"> <strong>Text</strong></a> </div> With normal tags like XML ones it is easy, you just create the class with the same name as the tag, so if the tag is: <something></something> you create a class called something, but how would you do this in HTML in an example div such as that one, with a class attribute inside?

    Read the article

  • Is it possible to Serialize and Deserialize objects in C++?

    - by GK
    As we know c++ is also an Object Oriented Programming language where most the things are objects like java. So wanted to know is the Serialize and deserializ features are available in c++ as well as we do it in java? If yes how it can be achieved? In java We use Serializable Interface to say that this type of object can be serialized and deserialized. So in c++ how? And out of curiosity is it same in c# as in java?

    Read the article

  • Beginner: 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. Now I tried to deserialize like so: public class Deserialize { static Deserialize ds; MyFrame frame; public static void main(String[] args) { try { ds.deserialize(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void deserialize() throws ClassNotFoundException { 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(); } } } Maybe somebody could point me into the direction where my misconception is? Thx in advance!

    Read the article

  • ASP.NET: Serializing and deserializing JSON objects

    - by DigiMortal
    ASP.NET offers very easy way to serialize objects to JSON format. Also it is easy to deserialize JSON objects using same library. In this posting I will show you how to serialize and deserialize JSON objects in ASP.NET. All required classes are located in System.Servicemodel.Web assembly. There is namespace called System.Runtime.Serialization.Json for JSON serializer. To serialize object to stream we can use the following code. var serializer = new DataContractJsonSerializer(typeof(MyClass)); serializer.WriteObject(myStream, myObject); To deserialize object from stream we can use the following code. CopyStream() is practically same as my Stream.CopyTo() extension method. var serializer = new DataContractJsonSerializer(typeof(MyClass));   using(var stream = response.GetResponseStream()) using (var ms = new MemoryStream()) {     CopyStream(stream, ms);     results = serializer.ReadObject(ms) as MyClass; } Why I copied data from response stream to memory stream? Point is simple – serializer uses some stream features that are not supported by response stream. Using memory stream we can deserialize object that came from web.

    Read the article

  • Deserializing a type at the current stream position with protobuf-net

    - by Arne Claassen
    I'm serializing several objects into a single stream, but when i try to read them back, i can't seem to get anything but the last object: ProtoBuf.Serializer.Serialize(stream, postA1); ProtoBuf.Serializer.Serialize(stream, postB2); stream.Position = 0; var postA2 = ProtoBuf.Serializer.Deserialize<Post>(stream); var postB2 = ProtoBuf.Serializer.Deserialize<Post>(stream); The first deserialize moves the stream to the end and postA2 contains the value of postB2, while postB2 is just an uninitialized instance. Is this expected behavior, and if so, how do you deserialize an object from a random position in a stream?

    Read the article

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