Search Results

Search found 1392 results on 56 pages for 'serialization'.

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

  • Gson serialization depending on field value

    - by Serj Lotutovici
    I have a POJO that is similar to: public class MyGsonPojo { @Expose @SerializedName("value1") private String valueOne; @Expose @SerializedName("value2") private boolean valueTwo; @Expose @SerializedName("value3") private int valueThree; // Getters and other stuff here } The issue is that this object has to be serialized into a json body for a call to the server. Some fields are optional for the request and if I even send it with default and null values, the API responds differently (Unfortunately changing the api is not an option). So basically I need to exclude fields from serialization if any of them is set to a default value. For example if the field valueOne is null the resulting json should be: { "value2" : true, "value3" : 2 } Any idea how to make this a painless effort? I wouldn't want to build the json body manually. Any help would be great. Thank you in advice.

    Read the article

  • AppFabric serialization problem.

    - by jandark
    I am trying cache a class instance with AppFabric but it return class instance with empty members. The reason is DataContract Attribute. My class is marked with [Serializable] and [DataContract(Name = "TestClass", Namespace = "CustomNameSpace.TestClass")] attributes. Problem solving if I mark all properties with DataMember or remove DataContract attribute. But I do not want to remove DataContract attributte because of other serialization needs (such as json or something else) Or I do not want to add DataMember attribute to other classes. (a lot of) Do you have any idea to solve that problem ? Thanks.

    Read the article

  • what is serialization and how it works

    - by Rozer
    I know the serialization process but have't implemented it. In my application i have seen there are various classes that has been implemented serilizable interface. consider following class public class DBAccessRequest implements Serializable { private ActiveRequest request = null; private Connection connection = null; private static Log log = LogFactory.getLog(DBAccessRequest.class); public DBAccessRequest(ActiveRequest request,Connection connection) { this.request = request; this.connection = connection; } /** * @return Returns the DB Connection object. */ public Connection getConnection() { return connection; } /** * @return Returns the active request object for the db connection. */ public ActiveRequest getRequest() { return request; } } just setting request and connection in constructor and having getter setter for them. so what is the use of serilizable implementation over here...

    Read the article

  • Simple way of converting server side objects into client side using JSON serialization for asp.net websites

    - by anil.kasalanati
     Introduction:- With the growth of Web2.0 and the need for faster user experience the spotlight has shifted onto javascript based applications built using REST pattern or asp.net AJAX Pagerequest manager. And when we are working with javascript wouldn’t it be much better if we could create objects in an OOAD way and easily push it to the client side.  Following are the reasons why you would push the server side objects onto client side -          Easy availability of the complex object. -          Use C# compiler and rick intellisense to create and maintain the objects but use them in the javascript. You could run code analysis etc. -          Reduce the number of calls we make to the server side by loading data on the pageload.   I would like to explain about the 3rd point because that proved to be highly beneficial to me when I was fixing the performance issues of a major website. There could be a scenario where in you be making multiple AJAX based webrequestmanager calls in order to get the same response in a single page. This happens in the case of widget based framework when all the widgets are independent but they need some common information available in the framework to load the data. So instead of making n multiple calls we could load the data needed during pageload. The above picture shows the scenario where in all the widgets need the common information and then call GetData webservice on the server side. Ofcourse the result can be cached on the client side but a better solution would be to avoid the call completely.  In order to do that we need to JSONSerialize the content and send it in the DOM.                                                                                                                                                                                                                                                                                                                                                                                            Example:- I have developed a simple application to demonstrate the idea and I would explaining that in detail here. The class called SimpleClass would be sent as serialized JSON to the client side .   And this inherits from the base class which has the implementation for the GetJSONString method. You can create a single base class and all the object which need to be pushed to the client side can inherit from that class. The important thing to note is that the class should be annotated with DataContract attribute and the methods should have the Data Member attribute. This is needed by the .Net DataContractSerializer and this follows the opt-in mode so if you want to send an attribute to the client side then you need to annotate the DataMember attribute. So if I didn’t want to send the Result I would simple remove the DataMember attribute. This is default WCF/.Net 3.5 stuff but it provides the flexibility of have a fullfledged object on the server side but sending a smaller object to the client side. Sometimes you may hide some values due to security constraints. And thing you will notice is that I have marked the class as Serializable so that it can be stored in the Session and used in webfarm deployment scenarios. Following is the implementation of the base class –  This implements the default DataContractJsonSerializer and for more information or customization refer to following blogs – http://softcero.blogspot.com/2010/03/optimizing-net-json-serializing-and-ii.html http://weblogs.asp.net/gunnarpeipman/archive/2010/12/28/asp-net-serializing-and-deserializing-json-objects.aspx The next part is pretty simple, I just need to inject this object into the aspx page.   And in the aspx markup I have the following line – <script type="text/javascript"> var data =(<%=SimpleClassJSON  %>);   alert(data.ResultText); </script>   This will output the content as JSON into the variable data and this can be any element in the DOM. And you can verify the element by checking data in the Firebug console.    Design Consideration – If you have a lot of javascripts then you need to think about using Script # and you can write javascript in C#. Refer to Nikhil’s blog – http://projects.nikhilk.net/ScriptSharp Ensure that you are taking security into consideration while exposing server side objects on to client side. I have seen application exposing passwords, secret key so it is not a good practice.   The application can be tested using the following url – http://techconsulting.vpscustomer.com/Samples/JsonTest.aspx The source code is available at http://techconsulting.vpscustomer.com/Source/HistoryTest.zip

    Read the article

  • XStream <-> Alternative binary formats (e.g. protocol buffers)

    - by sehugg
    We currently use XStream for encoding our web service inputs/outputs in XML. However we are considering switching to a binary format with code generator for multiple languages (protobuf, Thrift, Hessian, etc) to make supporting new clients easier and less reliant on hand-coding (also to better support our message formats which include binary data). However most of our objects on the server are POJOs with XStream handling the serialization via reflection and annotations, and most of these libraries assume they will be generating the POJOs themselves. I can think of a few ways to interface an alternative library: Write an XStream marshaler for the target format. Write custom code to marshal the POJOs to/from the classes generated by the alternative library. Subclass the generated classes to implement the POJO logic. May require some rewriting. (Also did I mention we want to use Terracotta?) Use another library that supports both reflection (like XStream) and code generation. However I'm not sure which serialization library would be best suited to the above techniques.

    Read the article

  • Silverlight WCF serialization DataContract(IsReference=true) problem

    - by Ciaran
    Hi, I'm have a Silverlight 3 UI that access WCF services which in turn access respositories that use NHibernate. To overcome some NHibernate lazy loading issues with WCF I'm using my own DataContract surrogate as described here: http://timvasil.com/blog14/post/2008/02/WCF-serialization-with-NHibernate.aspx. In here I'm setting preserveObjectReferences = true My model contains cycles (i.e. Customer with IList[Order]) When I retrieve an object from my service it works fine, however when I try and send that same object back to the wcf service I get the error: System.ServiceModel.CommunicationException was unhandled by user code Message=There was an error while trying to serialize parameter http://tempuri.org/:searchCriteria. The InnerException message was 'Object graph ...' contains cycles and cannot be serialized if references are not tracked. Consider using the DataContractAttribute with the IsReference property set to true.' So cyclical references are now a problem in Silverlight, so I try change my DataContract to be [DataContract(IsReference=true)] but now when I try to retrieve an object from my service I get the following exception: System.ExecutionEngineException was unhandled Message=Exception of type 'System.ExecutionEngineException' was thrown. InnerException: Any ideas?

    Read the article

  • Silverlight WCF serialization [DataContract(IsReference=true)] problem

    - by Ciaran
    Hi, I'm have a Silverlight 3 UI that access WCF services which in turn access respositories that use NHibernate. To overcome some NHibernate lazy loading issues with WCF I'm using my own DataContract surrogate as described here: http://timvasil.com/blog14/post/2008/02/WCF-serialization-with-NHibernate.aspx. In here I'm setting preserveObjectReferences = true My model contains cycles (i.e. Customer with Collection). When I retrieve an object from my service it works fine, however when I try and send that same object back to the wcf service I get the error: System.ServiceModel.CommunicationException was unhandled by user code Message=There was an error while trying to serialize parameter http://tempuri.org/:searchCriteria. The InnerException message was 'Object graph ...' contains cycles and cannot be serialized if references are not tracked. Consider using the DataContractAttribute with the IsReference property set to true.' So cyclical references are now a problem in Silverlight, so I try change my DataContract to be [DataContract(IsReference=true)] but now when I try to retrieve an object from my service I get the following exception: System.ServiceModel.CommunicationException was unhandled by user code Message=The remote server returned an error: NotFound. It shouldn't be this hard to do something so trivial...

    Read the article

  • Data Contract Serialization Not Working For All Elements

    - by splatto
    I have an XML file that I'm trying to serialize into an object. Some elements are being ignored. My XML File: <?xml version="1.0" encoding="utf-8" ?> <License xmlns="http://schemas.datacontract.org/2004/07/MyApp.Domain"> <Guid>7FF07F74-CD5F-4369-8FC7-9BF50274A8E8</Guid> <Url>http://www.gmail.com</Url> <ValidKey>true</ValidKey> <CurrentDate>3/1/2010 9:39:28 PM</CurrentDate> <RegistrationDate>3/8/2010 9:39:28 PM</RegistrationDate> <ExpirationDate>3/8/2099 9:39:28 PM</ExpirationDate> </License> My class definition: [DataContract] public class License { [DataMember] public virtual int Id { get; set; } [DataMember] public virtual string Guid { get; set; } [DataMember] public virtual string ValidKey { get; set; } [DataMember] public virtual string Url { get; set; } [DataMember] public virtual string CurrentDate { get; set; } [DataMember] public virtual string RegistrationDate { get; set; } [DataMember] public virtual string ExpirationDate { get; set; } } And my Serialization attempt: XmlDocument Xmldoc = new XmlDocument(); Xmldoc.Load(string.Format(url)); string xml = Xmldoc.InnerXml; var serializer = new DataContractSerializer(typeof(License)); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)); License license = (License)serializer.ReadObject(memoryStream); memoryStream.Close(); The following elements are serialized: Guid ValidKey The following elements are not serialized: Url CurrentDate RegistrationDate ExpirationDate Replacing the string dates in the xml file with "blah" doesn't work either. What gives?

    Read the article

  • XML Serialization Not Working For All Elements (C#)

    - by splatto
    I have an XML file that I'm trying to serialize into an object. Some elements are being ignored. My XML File: <?xml version="1.0" encoding="utf-8" ?> <License xmlns="http://schemas.datacontract.org/2004/07/MyApp.Domain"> <Guid>7FF07F74-CD5F-4369-8FC7-9BF50274A8E8</Guid> <Url>http://www.gmail.com</Url> <ValidKey>true</ValidKey> <CurrentDate>3/1/2010 9:39:28 PM</CurrentDate> <RegistrationDate>3/8/2010 9:39:28 PM</RegistrationDate> <ExpirationDate>3/8/2099 9:39:28 PM</ExpirationDate> </License> My class definition: [DataContract] public class License { [DataMember] public virtual int Id { get; set; } [DataMember] public virtual string Guid { get; set; } [DataMember] public virtual string ValidKey { get; set; } [DataMember] public virtual string Url { get; set; } [DataMember] public virtual string CurrentDate { get; set; } [DataMember] public virtual string RegistrationDate { get; set; } [DataMember] public virtual string ExpirationDate { get; set; } } And my Serialization attempt: XmlDocument Xmldoc = new XmlDocument(); Xmldoc.Load(string.Format(url)); string xml = Xmldoc.InnerXml; var serializer = new DataContractSerializer(typeof(License)); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)); License license = (License)serializer.ReadObject(memoryStream); memoryStream.Close(); The following elements are serialized: Guid ValidKey The following elements are not serialized: Url CurrentDate RegistrationDate ExpirationDate Replacing the string dates in the xml file with "blah" doesn't work either. What gives?

    Read the article

  • Serialization Performance and Google Android

    - by Jomanscool2
    I'm looking for advice to speed up serialization performance, specifically when using the Google Android. For a project I am working on, I am trying to relay a couple hundred objects from a server to the Android app, and am going through various stages to get the performance I need. First I tried a terrible XML parser that I hacked together using Scanner specifically for this project, and that caused unbelievably slow performance when loading the objects (~5 minutes for a 300KB file). I then moved away from that and made my classes implement Serializable and wrote the ArrayList of objects I had to a file. Reading that file into the objects the Android, with the file already downloaded mind you, was taking ~15-30 seconds for the ~100KB serialized file. I still find this completely unacceptable for an Android app, as my app requires loading the data when starting the application. I have read briefly about Externalizable and how it can increase performance, but I am not sure as to how one implements it with nested classes. Right now, I am trying to store an ArrayList of the following class, with the nested classes below it. public class MealMenu implements Serializable{ private String commonsName; private long startMillis, endMillis, modMillis; private ArrayList<Venue> venues; private String mealName; } And the Venue class: public class Venue implements Serializable{ private String name; private ArrayList<FoodItem> foodItems; } And the FoodItem class: public class FoodItem implements Serializable{ private String name; private boolean vegan; private boolean vegetarian; } IF Externalizable is the way to go to increase performance, is there any information as to how java calls the methods in the objects when you try to write it out? I am not sure if I need to implement it in the parent class, nor how I would go about serializing the nested objects within each object.

    Read the article

  • java serialization problems with different JVMs

    - by Alberto
    I am having trouble using serialization in Java. I've searched the web for a solution but haven't found an answer yet. The problem is this - I have a Java library (I have the code and I export it to an archive prior to executing the code) which I need to use with two differents JVMs. One JVM is on the server (Ubuntu, running Java(TM) JRE SE Runtime Environment (build 1.7.0_09-b05)) and the other on Android 2.3.3. I compiled the library in Java 1.6. Now, I am trying to import to the client, an object exported from the server, but I receive this error: java.io.InvalidClassException: [Lweka.classifiers.functions.MultilayerPerceptron$NeuralEnd;; Incompatible class (SUID): [Lweka.classifiers.functions.MultilayerPerceptron$NeuralEnd;: static final long serialVersionUID =-359311387972759020L; but expected [Lweka.classifiers.functions.MultilayerPerceptron$NeuralEnd;: static final long serialVersionUID =1920571045915494592L; I do have an explicit serial version UID declared on the class MultilayerPerceptron$NeuralEnd, like this: protected class NeuralEnd extends NeuralConnection { private static final long serialVersionUID = 7305185603191183338L; } Where NeuralConnection implements the java.io.Serializable interface. If I do a serialver on MultilayerPerceptron$NeuralEnd I receive the serialVersionUID which I declared. So, why have both JVMs changed this value? Can you help me? Thanks, Alberto

    Read the article

  • Virtual properties duplicated during serialization when XmlElement attribute used

    - by Laramie
    The Goal: XML serialize an object that contains a list of objects of that and its derived types. The resulting XML should not use the xsi:type attribute to describe the type, to wit the names of the serialized XML elements would be an assigned name specific to the derived type, not always that of the base class, which is the default behavior. The Attempt: After exploring IXmlSerializable and IXmlSerializable with eerie XmlSchemaProvider methods and voodoo reflection to return specialized schemas and an XmlQualifiedName over the course of days, I found I was able to use the simple [XmlElement] attribute to accomplish the goal... almost. The Problem: Overridden properties appear twice when serializing. The exception reads "The XML element 'overriddenProperty' from namespace '' is already present in the current scope. Use XML attributes to specify another XML name or namespace for the element." I attempted using a *Specified property (see code), but it didn't work. Sample Code: Class Declaration using System; using System.Collections.Generic; using System.Xml.Serialization; [XmlInclude(typeof(DerivedClass))] public class BaseClass { public BaseClass() { } [XmlAttribute("virt")] public virtual string Virtual { get; set; } [XmlIgnore] public bool VirtualSpecified { get { return (this is BaseClass); } set { } } [XmlElement(ElementName = "B", Type = typeof(BaseClass), IsNullable = false)] [XmlElement(ElementName = "D", Type = typeof(DerivedClass), IsNullable = false)] public List<BaseClass> Children { get; set; } } public class DerivedClass : BaseClass { public DerivedClass() { } [XmlAttribute("virt")] public override string Virtual { get { return "always return spackle"; } set { } } } Driver: BaseClass baseClass = new BaseClass() { Children = new List<BaseClass>() }; BaseClass baseClass2 = new BaseClass(){}; DerivedClass derivedClass1 = new DerivedClass() { Children = new List<BaseClass>() }; DerivedClass derivedClass2 = new DerivedClass() { Children = new List<BaseClass>() }; baseClass.Children.Add(derivedClass1); baseClass.Children.Add(derivedClass2); derivedClass1.Children.Add(baseClass2); I've been wrestling with this on and off for weeks and can't find the answer anywhere.

    Read the article

  • Cross-platform and language (de)serialization

    - by fwgx
    I'm looking for a way to serialize a bunch of C++ structs in the most convenient way so that the serialization is portable across C++ and Java (at a minimum) and across 32bit/64bit, big/little endian platforms. The structures to be serialized just contain data, i.e. they're pure data objects with no state or behavior. The idea being that we serialize the structs into an octet blob that we can store in a database "generically" and be read out later on. Thus avoiding changing the database whenever a struct changes and also avoiding assigning each data member to a field - i.e. we only want one table to hold everything "generically" as a binary blob. This should make less work for developers and require less changes when structures change. I've looked at boost.serialize but don't think there's a way to enable compatibility with Java. And likewise for inheriting Serializable in Java. If there is a way to do it by starting with an IDL file that would be best as we already have IDL files that describe the structures. Cheers in advance!

    Read the article

  • Really simple JSON serialization in .NET

    - by Evgeny
    I have some simple .NET objects I'd like to serialize to JSON and back again. The set of objects to be serialized is quite small and I control the implementation, so I don't need a generic solution that will work for everything. Since my assembly will be distributed as a library I'd really like to avoid a dependency on some third-party DLL: I just want to give users one assembly that they can reference. I've read the other questions I could find on converting to and from JSON in .NET. The recommended solution of JSON.NET does work, of course, but it requires distributing an extra DLL. I don't need any of the fancy features of JSON.NET. I just need to handle a simple object (or even dictionary) that contains strings, integers, DateTimes and arrays of strings and bytes. On deserializing I'm happy to get back a dictionary - it doesn't need to create the object again. Is there some really simple code out there that I could compile into my assembly to do this simple job? I've also tried System.Web.Script.Serialization.JavaScriptSerializer, but where it falls down is the byte array: I want to base64-encode it and even registering a converter doesn't let me easily accomplish that due to the way that API works (it doesn't pass in the name of the field).

    Read the article

  • Looking for a fast, compact, streamable, multi-language, strongly typed serialization format

    - by sanity
    I'm currently using JSON (compressed via gzip) in my Java project, in which I need to store a large number of objects (hundreds of millions) on disk. I have one JSON object per line, and disallow linebreaks within the JSON object. This way I can stream the data off disk line-by-line without having to read the entire file at once. It turns out that parsing the JSON code (using http://www.json.org/java/) is a bigger overhead than either pulling the raw data off disk, or decompressing it (which I do on the fly). Ideally what I'd like is a strongly-typed serialization format, where I can specify "this object field is a list of strings" (for example), and because the system knows what to expect, it can deserialize it quickly. I can also specify the format just by giving someone else its "type". It would also need to be cross-platform. I use Java, but work with people using PHP, Python, and other languages. So, to recap, it should be: Strongly typed Streamable (ie. read a file bit by bit without having to load it all into RAM at once) Cross platform (including Java and PHP) Fast Free (as in speech) Any pointers?

    Read the article

  • django: control json serialization

    - by abolotnov
    Is there a way to control json serialization in django? Simple code below will return serialized object in json: co = Collection.objects.all() c = serializers.serialize('json',co) The json will look similar to this: [ { "pk": 1, "model": "picviewer.collection", "fields": { "urlName": "architecture", "name": "\u0413\u043e\u0440\u043e\u0434 \u0438 \u0430\u0440\u0445\u0438\u0442\u0435\u043a\u0442\u0443\u0440\u0430", "sortOrder": 0 } }, { "pk": 2, "model": "picviewer.collection", "fields": { "urlName": "nature", "name": "\u041f\u0440\u0438\u0440\u043e\u0434\u0430", "sortOrder": 1 } }, { "pk": 3, "model": "picviewer.collection", "fields": { "urlName": "objects", "name": "\u041e\u0431\u044a\u0435\u043a\u0442\u044b \u0438 \u043d\u0430\u0442\u044e\u0440\u043c\u043e\u0440\u0442", "sortOrder": 2 } } ] You can see it's serializing it in a way that you are able to re-create the whole model, shall you want to do this at some point - fair enough, but not very handy for simple JS ajax in my case: I want bring the traffic to minimum and make the whole thing little clearer. What I did is I created a view that passes the object to a .json template and the template will do something like this to generate "nicer" json output: [ {% if collections %} {% for c in collections %} {"id": {{c.id}},"sortOrder": {{c.sortOrder}},"name": "{{c.name}}","urlName": "{{c.urlName}}"}{% if not forloop.last %},{% endif %} {% endfor %} {% endif %} ] This does work and the output is much (?) nicer: [ { "id": 1, "sortOrder": 0, "name": "????? ? ???????????", "urlName": "architecture" }, { "id": 2, "sortOrder": 1, "name": "???????", "urlName": "nature" }, { "id": 3, "sortOrder": 2, "name": "??????? ? ?????????", "urlName": "objects" } ] However, I'm bothered by the fast that my solution uses templates (an extra step in processing and possible performance impact) and it will take manual work to maintain shall I update the model, for example. I'm thinking json generating should be part of the model (correct me if I'm wrong) and done with either native python-json and django implementation but can't figure how to make it strip the bits that I don't want. One more thing - even when I restrict it to a set of fields to serialize, it will keep the id always outside the element container and instead present it as "pk" outside of it.

    Read the article

  • final transient fields and serialization

    - by doublep
    Is it possible to have final transient fields that are set to any non-default value after serialization in Java? My usecase is a cache variable — that's why it is transient. I also have a habit of making Map fields that won't be changed (i.e. contents of the map is changed, but object itself remains the same) final. However, these attributes seem to be contradictory — while compiler allows such a combination, I cannot have the field set to anything but null after unserialization. I tried the following, without success: simple field initialization (shown in the example): this is what I normally do, but the initialization doesn't seem to happen after unserialization; initialization in constructor (I believe this is semantically the same as above though); assigning the field in readObject() — cannot be done since the field is final. In the example cache is public only for testing. import java.io.*; import java.util.*; public class test { public static void main (String[] args) throws Exception { X x = new X (); System.out.println (x + " " + x.cache); ByteArrayOutputStream buffer = new ByteArrayOutputStream (); new ObjectOutputStream (buffer).writeObject (x); x = (X) new ObjectInputStream (new ByteArrayInputStream (buffer.toByteArray ())).readObject (); System.out.println (x + " " + x.cache); } public static class X implements Serializable { public final transient Map <Object, Object> cache = new HashMap <Object, Object> (); } } Output: test$X@1a46e30 {} test$X@190d11 null

    Read the article

  • .NET binary serialization conditionally without ISerializable

    - by SillyWhy
    I got 2 classes, for example: public class A { private B b; ... } public class B { ... } I need to serialize an object A using BinaryFormatter. When remoting it shall include the field b, but not when serialize to file. Here is what I added: [Serializable] public class A : MarshalByRefObject { private B b; [OnSerializing] private void OnSerializing(StreamingContext context) { if (context.State == StreamingContextStates.File) { this.b = null; } } ... } [Serializable] public class B : MarshalByRefObject { ... } I think this is a bad design because if another class C also contains B, in class C we must add the duplicate OnSerializing() logic as in A. Class B should decide what to do, not class A or C. I don't want to use ISerializable interface because there are too many variables in class B have to be added to SerializationInfo. I can create a SerializationSurrogate for class B, which perform nothing in GetObjectData() & SetObjectData(), then use it when serializing to file. However the same maintenance issue because whoever modify class B can't notice what going to happen during serialization & the existence of SerializationSurrogate. Is there a better alternative?

    Read the article

  • C#: Determine Type for (De-)Serialization

    - by dbemerlin
    Hi, i have a little problem implementing some serialization/deserialization logic. I have several classes that each take a different type of Request object, all implementing a common interface and inheriting from a default implementation: This is how i think it should be: Requests interface IRequest { public String Action {get;set;} } class DefaultRequest : IRequest { public String Action {get;set;} } class LoginRequest : DefaultRequest { public String User {get;set;} public String Pass {get;set;} } Handlers interface IHandler<T> { public Type GetRequestType(); public IResponse HandleRequest(IModel model, T request); } class DefaultHandler<T> : IHandler<T> // Used as fallback if the handler cannot be determined { public Type GetRequestType() { return /* ....... how to get the Type of T? ((new T()).GetType()) ? .......... */ } public IResponse HandleRequest(IModel model, T request) { /* ... */ } } class LoginHandler : DefaultHandler<LoginRequest> { public IResponse HandleRequest(IModel mode, LoginRequest request) { } } Calling class Controller { public ProcessRequest(String action, String serializedRequest) { IHandler handler = GetHandlerForAction(action); IRequest request = serializer.Deserialize<handler.GetRequestType()>(serializedRequest); handler(this.Model, request); } } Is what i think of even possible? My current Solution is that each handler gets the serialized String and is itself responsible for deserialization. This is not a good solution as it contains duplicate code, the beginning of each HandleRequest method looks the same (FooRequest request = Deserialize(serializedRequest); + try/catch and other Error Handling on failed deserialization). Embedding type information into the serialized Data is not possible and not intended. Thanks for any Hints.

    Read the article

  • remove versioning on boost xml serialization

    - by cppanda
    hi, i just can't find a way to remove the version tracking from the boost xmlarchives. example <Settings class_id="0" tracking_level="0" version="1"> <px class_id="1" tracking_level="1" version="0" object_id="_0"> <TestInt>3</TestInt> <Resolution class_id="2" tracking_level="0" version="0"> <x>800</x> <y>600</y> </Resolution> <SomeStuff>0</SomeStuff> </px> </Settings> I want to get ride of the class_id="0" tracking_level="0" version="1" stuff, because for in this case i just don't need it and want a simple clean config like file code void serialize(Archive & ar, const unsigned int version) { ar & make_nvp("TestInt", TestInt); ar & make_nvp("Resolution", resolution); ar & make_nvp("SomeStuff", SomeStuff); } i found boost::serialization::track_never, but nowhere to use it

    Read the article

  • How to implement Xml Serialization with inherited classes in C#

    - by liorafar
    I have two classes : base class name Component and inheritd class named DBComponent [Serializable] public class Component { private string name = string.Empty; private string description = string.Empty; } [Serializable] public class DBComponent : Component { private List<string> spFiles = new List<string>(); // Storage Procedure Files [XmlArrayItem("SPFile", typeof(string))] [XmlArray("SPFiles")] public List<string> SPFiles { get { return spFiles; } set { spFiles = value; } } public DBComponent(string name, string description) : base(name, description) { } } [Serializable] public class ComponentsCollection { private static ComponentsCollection instance = null; private List<Component> components = new List<Component>(); public List<Component> Components { get { return components; } set { components = value; } } public static ComponentsCollection GetInstance() { if (ccuInstance == null) { lock (lockObject) { if (instance == null) PopulateComponents(); } } return instance; } private static void PopulateComponents() { instance = new CCUniverse(); XmlSerializer xs = new XmlSerializer(instance.GetType()); instance = xs.Deserialize(XmlReader.Create("Components.xml")) as ComponentsCollection; } } } I want read\write from a Xml file. I know that I need to implement the Serialization for DBComponent class otherwise it will not read it.But i cannot find any simple article for that. all the articles that I found were too complex for this simple scenario. The Xml file looks like this: <?xml version="1.0" encoding="utf-8" ?> <ComponentsCollection> <Components> <DBComponent Name="Tenant Historical Database" Description="Tenant Historical Database"> <SPFiles> <SPFile>Setup\TenantHistoricalSP.sql</SPFile> </SPFiles> </DBComponent> <Component Name="Agent" Description="Desktop Agent" /> </Components> </ComponentsCollection> Can someone please give me a simple example of how to read this kind of xml file and what should be implemented ? Thanks Lior

    Read the article

  • C# Serialization Surrogate - Cannot access a disposed object

    - by crushhawk
    I have an image class (VisionImage) that is a black box to me. I'm attempting to serialize the image object to file using Serialization Surrogates as explained on this page. Below is my surrogate code. sealed class VisionImageSerializationSurrogate : ISerializationSurrogate { public void GetObjectData(Object obj, SerializationInfo info, StreamingContext context) { VisionImage image = (VisionImage)obj; byte[,] temp = image.ImageToArray().U8; info.AddValue("width", image.Width); info.AddValue("height", image.Height); info.AddValue("pixelvalues", temp, temp.GetType()); } public Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { VisionImage image = (VisionImage)obj; Int32 width = info.GetInt32("width"); Int32 height = info.GetInt32("height"); byte[,] temp = new byte[height, width]; temp = (byte[,])info.GetValue("pixelvalues", temp.GetType()); PixelValue2D tempPixels = new PixelValue2D(temp); image.ArrayToImage(tempPixels); return image; } } I've stepped through it to write to binary. It seems to be working fine (file is getting bigger as the images are captured). I tried to test it read the file back in. The values read back in are correct as far as the "info" object is concerned. When I get to the line image.ArrayToImage(tempPixels); It throws the "Cannot access a disposed object" exception. Upon further inspection, the object and the resulting image are both marked as disposed. My code behind the form spawns an "acquisitionWorker" and runs the following code. void acquisitionWorker_LoadImages(object sender, DoWorkEventArgs e) { // This is the main function of the acquisition background worker thread. // Perform image processing here instead of the UI thread to avoid a // sluggish or unresponsive UI. BackgroundWorker worker = (BackgroundWorker)sender; try { uint bufferNumber = 0; // Loop until we tell the thread to cancel or we get an error. When this // function completes the acquisitionWorker_RunWorkerCompleted method will // be called. while (!worker.CancellationPending) { VisionImage savedImage = (VisionImage) formatter.Deserialize(fs); CommonAlgorithms.Copy(savedImage, imageViewer.Image); // Update the UI by calling ReportProgress on the background worker. // This will call the acquisition_ProgressChanged method in the UI // thread, where it is safe to update UI elements. Do not update UI // elements directly in this thread as doing so could result in a // deadlock. worker.ReportProgress(0, bufferNumber); bufferNumber++; } } catch (ImaqException ex) { // If an error occurs and the background worker thread is not being // cancelled, then pass the exception along in the result so that // it can be handled in the acquisition_RunWorkerCompleted method. if (!worker.CancellationPending) e.Result = ex; } } What am I missing here? Why would the object be immediately disposed?

    Read the article

  • Haskell data serialization of some data implementing a common type class

    - by Evan
    Let's start with the following data A = A String deriving Show data B = B String deriving Show class X a where spooge :: a -> Q [ Some implementations of X for A and B ] Now let's say we have custom implementations of show and read, named show' and read' respectively which utilize Show as a serialization mechanism. I want show' and read' to have types show' :: X a => a -> String read' :: X a => String -> a So I can do things like f :: String -> [Q] f d = map (\x -> spooge $ read' x) d Where data could have been [show' (A "foo"), show' (B "bar")] In summary, I wanna serialize stuff of various types which share a common typeclass so I can call their separate implementations on the deserialized stuff automatically. Now, I realize you could write some template haskell which would generate a wrapper type, like data XWrap = AWrap A | BWrap B deriving (Show) and serialize the wrapped type which would guarantee that the type info would be stored with it, and that we'd be able to get ourselves back at least an XWrap... but is there a better way using haskell ninja-ery? EDIT Okay I need to be more application specific. This is an API. Users will define their As, and Bs and fs as they see fit. I don't ever want them hacking through the rest of the code updating their XWraps, or switches or anything. The most i'm willing to compromise is one list somewhere of all the A, B, etc. in some format. Why? Here's the application. A is "Download a file from an FTP server." B is "convert from flac to mp3". A contains username, password, port, etc. information. B contains file path information. A and B are Xs, and Xs shall be called "Tickets." Q is IO (). Spooge is runTicket. I want to read the tickets off into their relevant data types and then write generic code that will runTicket on the stuff read' from the stuff on disk. At some point I have to jam type information into the serialized data.

    Read the article

  • Control XML serialization of generic types

    - by Luca
    I'm investigating about XML serialization, and since I use lot of dictionary, I would like to serialize them as well. I found the following solution for that (I'm quite proud of it! :) ). [XmlInclude(typeof(Foo))] public class XmlDictionary<TKey, TValue> { /// <summary> /// Key/value pair. /// </summary> public struct DictionaryItem { /// <summary> /// Dictionary item key. /// </summary> public TKey Key; /// <summary> /// Dictionary item value. /// </summary> public TValue Value; } /// <summary> /// Dictionary items. /// </summary> public DictionaryItem[] Items { get { List<DictionaryItem> items = new List<DictionaryItem>(ItemsDictionary.Count); foreach (KeyValuePair<TKey, TValue> pair in ItemsDictionary) { DictionaryItem item; item.Key = pair.Key; item.Value = pair.Value; items.Add(item); } return (items.ToArray()); } set { ItemsDictionary = new Dictionary<TKey,TValue>(); foreach (DictionaryItem item in value) ItemsDictionary.Add(item.Key, item.Value); } } /// <summary> /// Indexer base on dictionary key. /// </summary> /// <param name="key"></param> /// <returns></returns> public TValue this[TKey key] { get { return (ItemsDictionary[key]); } set { Debug.Assert(value != null); ItemsDictionary[key] = value; } } /// <summary> /// Delegate for get key from a dictionary value. /// </summary> /// <param name="value"></param> /// <returns></returns> public delegate TKey GetItemKeyDelegate(TValue value); /// <summary> /// Add a range of values automatically determining the associated keys. /// </summary> /// <param name="values"></param> /// <param name="keygen"></param> public void AddRange(IEnumerable<TValue> values, GetItemKeyDelegate keygen) { foreach (TValue v in values) ItemsDictionary.Add(keygen(v), v); } /// <summary> /// Items dictionary. /// </summary> [XmlIgnore] public Dictionary<TKey, TValue> ItemsDictionary = new Dictionary<TKey,TValue>(); } The classes deriving from this class are serialized in the following way: <XmlProcessList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Items> <DictionaryItemOfInt32Foo> <Key/> <Value/> </DictionaryItemOfInt32XmlProcess> <Items> This give me a good solution, but: How can I control the name of the element DictionaryItemOfInt32Foo What happens if I define a Dictionary<FooInt32, Int32> and I have the classes Foo and FooInt32? Is it possible to optimize the class above? THank you very much!

    Read the article

  • Node Serialization in NetBeans Platform 7.0

    - by Geertjan
    Node serialization makes sense when you're not interested in the data (since that should be serialized to a database), but in the state of the application. For example, when the application restarts, you want the last selected node to automatically be selected again. That's not the kind of information you'll want to store in a database, hence node serialization is not about data serialization but about application state serialization. I've written about this topic in October 2008, here and here, but want to show how to do this again, using NetBeans Platform 7.0. Somewhere I remember reading that this can't be done anymore and that's typically the best motivation for me, i.e., to prove that it can be done after all. Anyway, in a standard POJO/Node/BeanTreeView scenario, do the following: Remove the "@ConvertAsProperties" annotation at the top of the class, which you'll find there if you used the Window Component wizard. We're not going to use property-file based serialization, but plain old java.io.Serializable  instead. In the TopComponent, assuming it is named "UserExplorerTopComponent", typically at the end of the file, add the following: @Override public Object writeReplace() { //We want to work with one selected item only //and thanks to BeanTreeView.setSelectionMode, //only one node can be selected anyway: Handle handle = NodeOp.toHandles(em.getSelectedNodes())[0]; return new ResolvableHelper(handle); } public final static class ResolvableHelper implements Serializable { private static final long serialVersionUID = 1L; public Handle selectedHandle; private ResolvableHelper(Handle selectedHandle) { this.selectedHandle = selectedHandle; } public Object readResolve() { WindowManager.getDefault().invokeWhenUIReady(new Runnable() { @Override public void run() { try { //Get the TopComponent: UserExplorerTopComponent tc = (UserExplorerTopComponent) WindowManager.getDefault().findTopComponent("UserExplorerTopComponent"); //Get the display text to search for: String selectedDisplayName = selectedHandle.getNode().getDisplayName(); //Get the root, which is the parent of the node we want: Node root = tc.getExplorerManager().getRootContext(); //Find the node, by passing in the root with the display text: Node selectedNode = NodeOp.findPath(root, new String[]{selectedDisplayName}); //Set the explorer manager's selected node: tc.getExplorerManager().setSelectedNodes(new Node[]{selectedNode}); } catch (PropertyVetoException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } }); return null; } } Assuming you have a node named "UserNode" for a type named "User" containing a property named "type", add the bits in bold below to your "UserNode": public class UserNode extends AbstractNode implements Serializable { static final long serialVersionUID = 1L; public UserNode(User key) { super(Children.LEAF); setName(key.getType()); } @Override public Handle getHandle() { return new CustomHandle(this, getName()); } public class CustomHandle implements Node.Handle { static final long serialVersionUID = 1L; private AbstractNode node = null; private final String searchString; public CustomHandle(AbstractNode node, String searchString) { this.node = node; this.searchString = searchString; } @Override public Node getNode() { node.setName(searchString); return node; } } } Run the application and select one of the user nodes. Close the application. Start it up again. The user node is not automatically selected, in fact, the window does not open, and you will see this in the output: Caused: java.io.InvalidClassException: org.serialization.sample.UserNode; no valid constructor Read this article and then you'll understand the need for this class: public class BaseNode extends AbstractNode { public BaseNode() { super(Children.LEAF); } public BaseNode(Children kids) { super(kids); } public BaseNode(Children kids, Lookup lkp) { super(kids, lkp); } } Now, instead of extending AbstractNode in your UserNode, extend BaseNode. Then the first non-serializable superclass of the UserNode has an explicitly declared no-args constructor, Do the same as the above for each node in the hierarchy that needs to be serialized. If you have multiple nodes needing serialization, you can share the "CustomHandle" inner class above between all the other nodes, while all the other nodes will also need to extend BaseNode (or provide their own non-serializable super class that explicitly declares a no-args constructor). Now, when I run the application, I select a node, then I close the application, restart it, and the previously selected node is automatically selected when the application has restarted.

    Read the article

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