FAQ Database Discussion Community


Writing a serializer for Gson using Java 8

java,json,serialization,gson,java-8
I have a own class called MyDate and want to write a serializer of it for Gson. This code works: GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(MyDate.class, new JsonSerializer<MyDate>() { @Override public JsonElement serialize(MyDate date, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(date.toString()); } }); However I want to use the...

What is the difference between Spark Serialization and Java Serialization?

java,serialization,apache-spark
I'm using Spark + Yarn and I have a service that I want to call on distributed nodes. When I serialize this service object "by hand" in a Junit test using java serialization, all inner collections of the service are well serialized and deserialized : @Test public void testSerialization() {...

Rails serialize not storing correctly

ruby-on-rails,json,serialization,stripe-payments,stripe-connect
I am setting up stripe connect with the example from https://github.com/rfunduk/rails-stripe-connect-example and am running into a problem using serialize to store stripe_account_status which should be stored as an array. This is how it should be stored (Generated from the above example link) {"details_submitted"=>false, "charges_enabled"=>true, "transfers_enabled"=>false, "fields_needed"=>["legal_entity.first_name", "legal_entity.last_name", "legal_entity.dob.day", "legal_entity.dob.month", "legal_entity.dob.year",...

How to serialize only a very few properties in a Java class

java,serialization
Recently in an interview I was asked a question: There are 100 properties in a Java class and I should be able to serialize only 2 of the properties. How is this possible? Marking all the 98 properties was not the answer as it is not efficient. My answer was...

Custom (de-) serialize method throws java.io.OptionalDataException

java,serialization
When I serialize and then deserialize a map.subMap with my wrapping class I will run into a OptionalDataException. It seems that an OptionalDataException has to do with primitives but in a map I always have object boxed primitives right. So how can I solve this? EDIT: added synchronized block public...

Cheapest marker in java serialization?

java,serialization
I am using ObjectOutputStream's writeObject method to serialize a tree. The datatype of tree is generic, can be integer as well as a complex 'Student' object. But I need to 'mark' a null pointer, a pointer which I will use to mark leave node. eg: if (node.item == null) {...

C# Protobuf .NET Using Preexisting Byte Array

c#,networking,serialization,protobuf-net,objectpool
So I am working with Protobufs in .NET and I am trying to incorporate them with a buffer pool and AsyncSocketEventArgs pool. The buffer pool assigns sections of a huge byte array to the event args. So, the problem, I can't figure out a way to have Protobufs serialize directly...

core difference between set and serialized in cakephp 3.0?

serialization,cakephp-3.0
$player = $this->Players->get($id, [ 'contain' => [] ]); $this->set('player', $player); $this->set('_serialize', ['player']); if i will remove $this->set('_serialize', ['player']) than i am not getting any difference at my view. <h6 class="subheader"><?= __('First Name') ?></h6> <p><?= h($player->first_name) ?></p> <h6 class="subheader"><?= __('Last Name') ?></h6> <p><?= h($player->last_name) ?></p> <h6 class="subheader"><?= __('Email')...

Gson not deserializing JSON data

java,json,serialization,gson
I am trying to get some weather information from Yahoo APIs. This is my JSON: JSON This is my DTO: public class forecast implements Serializable { private static final long serialVersionUID = -520652416977871134L; private String text; private String high; private String day; private String code; private String low; private String...

org.apache.spark.SparkException: Task not serializable - JavaSparkContext

java,serialization,apache-spark
I'm trying to run the following simple Spark code: Gson gson = new Gson(); JavaRDD<String> stringRdd = jsc.textFile("src/main/resources/META-INF/data/supplier.json"); JavaRDD<SupplierDTO> rdd = stringRdd.map(new Function<String, SupplierDTO>() { private static final long serialVersionUID = -78238876849074973L; @Override public SupplierDTO call(String str) throws Exception { return gson.fromJson(str, SupplierDTO.class); } }); But it's throwing the following...

While Conditions for Deserializing Multiple Objects in Java

java,serialization
I am currently preparing for an evaluation for a Job Offer i have. So the company has given some practice assignments and their respective Solutions. I am facing a bit of dilemma on how to deserialize multiple objects from a Serialized file. Initially when i was solving on my own,...

Non-intruisive Boost serialization of labelled enums C++

c++,serialization,boost
I would like to serialize struct A where I could save the tag name of the enum expressions instead of its integer in a non intruisive way (without having to change struct A). enum e_fruit { apple, banana, coconut }; struct A { e_fruit fruit; int num; }; namespace boost...

Python - Load multiple Pickle objects into a single dictionary

python,serialization,pickle
So my problem is this... I have multiple Pickle object files (which are Pickled Dictionaries) and i want to load them all back up, but essentially merge each dictionary into a single larger dictionary. E.g. I have pickle_file1 and pickle_file2 both contain dictionaries. I would like the contents of pickle_file1...

ForeignKey ListField serialization on rest_framework with django-nonrel

django,mongodb,serialization,django-rest-framework,django-nonrel
I have a class called Collection class Collection(models.Model): slug = models.CharField(max_length=32, primary_key=True) name = models.CharField(max_length=200) description = models.TextField() user = models.ForeignKey(User) videos = ListField(models.ForeignKey(Video)) pub_date = models.DateTimeField('date published') objects = MongoDBManager() with a videos property that is a ListField of Video object ForeignKeys. When I try to Serialize Collection object...

Reading dictionary structure from text file in python

python,dictionary,serialization,deserialization
I have file where I have defined python dictionary: dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First', 'Friends': {'Emil':1, 'Frank':0} }; I want to read this dictionary and use it's element in python code. I've end up with following code: #!/usr/bin/python import sys import os import ast import re from...

How to send Java objects that are not defined structures in Thrift

java,serialization,deserialization,thrift
Is there a way to send Java objects that are not defined in thrift files as a structures from one java application to another java application via thrift. The problem is that we are using an external library that has it's own domain model and we need to send those...

Produce different serialized JSON for a given class in different scenarios

c#,json,serialization,asp.net-mvc-5,json.net
Update 1: for reasons I won't go into, I want to avoid having anything other than the properties to be persisted in my entity objects. This means no extra properties or methods... I have an entity called Entity1 with (say) 10 public properties. In one place in my code I...

Error during deserializing XML

c#,xml,serialization,deserialization
Class that I am serializing: public class StyleProperties { [XmlAttribute] public string Name; [XmlAttribute] public string Description; [XmlAttribute] public StyleType Type; public ShapeStyleProperties ShapeStyle; public TextStyleProperties TextStyle; } Part that is responsible for serializing data: XmlSerializer serializer = new XmlSerializer(typeof(StyleProperties)); PPT.Presentation pres = Globals.ThisAddIn.Application.ActivePresentation; CustomXMLParts parts = pres.CustomXMLParts; //var serializer...

Value Object vs Data Transfer Object

java,design-patterns,serialization,domain-driven-design,data-transfer-objects
I was a part of one of the project where we were producing java webservice and publishing into server. Some other java application was consuming the web service through extjs. In that producer application was following Domain Driven Design. We were using two types of pojos , Domain Objects and...

Serialize/Deserialize class containing byte array property into XML

c#,.net,xml,serialization,.net-4.0
My data class that will be serialized into XML look like this: [XmlType(TypeName = "SPCFileInfo")] [Serializable] public class SPCFileInfoProtocol { [XmlElement("CompanyCode")] public string CompanyCode { get; set; } [XmlElement("FileName")] public string FileName { get; set; } [XmlElement("FileVer")] public int FileVer { get; set; } [XmlElement("FileSize")] public long FileSize { get;...

Casting error from deserialized json in c# using newton json

c#,json,serialization,casting,json.net
Unable to cast to int from deserialized json (dictionary object) Here is the code: Lets say you have dictionary object. Dictionary<string, object> dict = new Dictionary<string, object>(); dict.Add("key", 1); Now i serialize & deserialize it. var serializedData = JsonConvert.SerializeObject(dict); var deserializedData = JsonConvert.DeserializeObject<Dictionary<string, object>>(serializedData); And getting error when i do...

Upgrade Compatibility of Boost Serialization with binary archives armv7 to arm64

c++,serialization,boost,boost-serialization,arm64
The company I work for releases on iOS and Android, and now Apple is requiring we update all of our apps to run on the arm64 architecture (previously we only released for armv7). Unfortunately we have been using boost::archive::binary_iarchive's (and binary_oarchive's) to store a lot of user data (saved games,...

Serializing into JSON using MemoryStream,while adding newlines C#

c#,json,serialization
I have to serialize some C# class data into JSON. For this purpose I use a MemoryStream and a DataContractJsonSerializer. MemoryStream stream1 = new MemoryStream(); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person)); ser.WriteObject(stream1, p); using (FileStream file = new FileStream("Write.json", FileMode.Create, FileAccess.ReadWrite)) { stream1.Position = 0; stream1.Read(stream1.ToArray(), 0, (int)stream1.Length); file.Write(stream1.ToArray(), 0, stream1.ToArray().Length);...

Serialization - not working

java,serialization
I create class with methods like a How to serialize an object into a string and it every say error "java.lang.ClassCastException: java.lang.String cannot be cast to Myclass" My codes: 1) import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import javax.xml.bind.DatatypeConverter; public class Serialization { public static...

Weirdness with Spark serialization

java,serialization,lambda,apache-spark
I've came accross a problem with Spark, using the JavaPairRdd.repartitionAndrepartitionAndSortWithinPartitions method. I've tried everything any reasonable person would have thought of. I finally written a small snippet simple enough to visualize the problem : public class Main { public static void main(String[] args) { SparkConf conf = new SparkConf().setAppName("test").setMaster("local"); JavaSparkContext...

POJOs to byte array vs POJOs to json

java,json,serialization
I'm a newbie at Java. I'm just confusing about serialization and deserialization. So, I'm confusing that which one I should use. I'm looking a round and found that Boon, Jackson, GSON (I'm currently using GSON, but some of article using Jackson and Boon) for JSON serialization. And serialize object...

How to pickle and unpickle to portable string in Python 3

python,python-3.x,serialization,unicode
I need to pickle a Python3 object to a string which I want to unpickle from an environmental variable in a Travis CI build. The problem is that I can't seem to find a way to pickle to a portable string (unicode) in Python3: import os, pickle from my_module import...

Serializing a treenode like data structure

c#,serialization
I'm struggling a little with my attempt to serialize the data used in my treeview, we use this as a form of caching data. Basically i have data such as follows PhotoGroup A PhotoGroup B PhotoGroup F PhotoGroup C PhotoGroup D PhotoGroup E As you (hopefully) can see, i have...

Error when serialize List

c#,serialization,windows-runtime,windows-phone-8.1
A am developing a Windows Phone Runtime application and a I have data in a string list. But when I suspend my app the error occurs Error trying to serialize the value to be written to the application data store and Additional information: Data of this type is not supported....

Need help to understand deserialization with ArrayList in Java

java,serialization,arraylist,casting,deserialization
I want write an ArrayList to a file and then read it back again. The list is going to hold Integer objects. Serialization seems to be working fine but I'm having trouble deserilaizing. More specifically I can'get the casting right. The serialization: ObjectOutputStream ou = new ObjectOutputStream(new FileOutputStream(new File("load.dat"))); ArrayList<Integer>...

Serialize byte array in JSON.NET without $type

c#,json,serialization,json.net
I would like to serialize all my contract with $type reference using TypeNameHandling.Objects. However when using this flag, all byte arrays (byte[]) are serialized using $value+$type. I still want Base64 encoding but without $type. For example, for the following contract: class MyClass { public byte[] MyBinaryProperty {get;set;} } I get:...

Jersey serializing null values to json : How to skip

java,json,spring,serialization,jersey-2.0
I am using Jersey 2.4 with spring. When I am returning a response from a method with an annotation @Produces(MediaType.APPLICATION_JSON) on it, it also serialize the null values to json. I don't want to serialize the fields that contains the null values. Is there any solution for the same?...

XML writer with repeating elements in node.js

javascript,json,xml,node.js,serialization
I'm trying to serialize an XML from a given object in node.js. I would like to serialize an array as some elements with the same name, i.e. the same element should be repeated. Example: var objectToSerialize = { SomeElement: { Data: [3, 5, 2] } }; serialize(objectToSerialize); Requested result: <RootElement>...

Why serialization is not required for InProc session mode

c#,asp.net,asp.net-mvc,session,serialization
I am using the state service session provider for my mvc application and if I don't serialize the type which I am going to store in session, application throws an error that class must be marked as Serializable. But if I switch to InProc session mode, session works even if...

Django SerializerDoesNotExist 'geojson'?

django,serialization,geojson,gdal
I'm trying to serialize data in the geojson format however whenever I use json = serialize("geojson", coordinate.objects.all()) response = HttpResponse(json) return response django gives me SerializerDoesNotExist at /getmarkers/ 'geojson' this works fine json = serialize("json", coordinate.objects.all()) surely anyone else who has tried using the geojson serializer has ran into the...

Serialize XML into CSharp class

c#,json,xml,visual-studio,serialization
I have a xml string in a json data field. I want to extract that value and compare that to the database's value for that field. I used xsd.exe to generate the class for that xml (saw from here). I am using that class to deserialize the xml response. Then...

Using Gson to serialize strings with \n in them

java,serialization,gson
\n in a string is effective in printing the text following \n in next line. However, if the same string is serialized using Gson, then \n is no more effective in printing it in next line. How can we fix this ? Sample program given below. In the program below,...

Serialise nested list or alternatives

c#,list,serialization,nested
I am trying to store a collection of lists (each containing over 20.000 int's) and was hoping to use a nested lest for this since each day a new list will be added. Eventually I need to access the data in the following way: "Take the first value of each...

JSON parsing using .NET deserialize() with nested “list”

javascript,c#,json,parsing,serialization
EDIT: Simplified the classes { "name": "Final Five", "bio": null, "noPlayers": "0", "roster": { "players0": { "playerId": "3516", "name": "Gate", "role": "Mid Lane", "isStarter": 1 }, "players1": { "playerId": "3826", "name": "Veritas", "role": "AD Carry", "isStarter": 1 }, "players2": { "playerId": "4054", "name": "Novel", "role": "Support", "isStarter": 1 }, "players3":...

Saving FileSystemInfo Array to File

c#,arrays,xml,file,serialization
I'm attempting to save an array of FileInfo and DirectoryInfo objects for use as a log file. The goal is to capture an image of a directory (and subdirectories) at a point in time for later comparison. I am currently using this class to store the info: public class myFSInfo...

Is there a way to automatically re-generate serialVersionId when class/code signature changes?

java,serialization
we have a whole bunch of serialized classes but want the database bits to be invalidated whenever the "signature" ie: field structure and serialization code for a class changes, Is there a utility that can generate a "hash" for a class file that will optimally detect when the serialization structure...

Deserializing Json String into multiple Object types

c#,json,serialization,json.net
I have a Json String that I get from a web service; it has a list of collections, each collection represents an object, for example: [ // Root List [ // First Collection : Team Object { "id": 1, "team_name": "Equipe Saidi", "is_active": true, "last_localisation_date": "2015-05-06T13:33:15+02:00" }, { "id": 3,...

django - “Incorrect type. Expected pk value, received str” error

django,serialization,foreign-keys,django-rest-framework
I my django-rest-framework I have the following models: Basically every ride has one final destination and can have multiple middle destinations. models.py: class Destination(models.Model): name=models.CharField(max_length=30) class Ride(models.Model): driver = models.ForeignKey('auth.User', related_name='rides_as_driver') destination=models.ForeignKey(Destination, related_name='rides_as_final_destination') leaving_time=models.TimeField() num_of_spots=models.IntegerField() passengers=models.ManyToManyField('auth.User',...

Need help converting JSON to C# Objects

c#,asp.net,json,object,serialization
I'm currently trying to convert a JSON string into C# objects and currently am experiencing trouble during my debugging. Below is a sample of the JSON along with my classes. Classes public class Timeline_RootObject { public List<Timeline_Frame> frames { get; set; } public int frameInterval { get; set; } }...

Deserializing arrays with protostuff

java,json,serialization,deserialization,protostuff
I am trying to use protostuff to serialize deserialize json but when i serialize the object the size of the array is put in front {"id":1,"price":1.2,"name":"alex","tags":{"a":3,"b":["tag1","tag2","tag2"]}} if i trie to desirialize the same string it works like a charm but my data dosent have "a":3,"b": for the tags its just...

Include a method when object is serialized in JMS

symfony2,serialization,jmsserializerbundle
I have a method that returns a value: /** * @ORM\Table() * @ORM\Entity(repositoryClass="PersonRepository") */ class Person { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; public function getFoo(){ return $this->id + 1; } //setters & getters } I would like to include the...

How do Django REST api serializers know what model they are associated with?

python,django,rest,serialization
I'm extremely new to Django. I've been researching Django as wells as the Django REST api for use with a project I'm doing and I've been browsing the documentation. I came across serialization here: http://www.django-rest-framework.org/api-guide/serializers/ and I'm just a little confused how the serializer knows which model it is associated...

Deserialize a json serialized CookieCollection

c#,serialization,json.net,json-deserialization,httpcookiecollection
In my code I have to Json serialize a CookieCollection object and pass it as string, to achieve this I do like this: var json = Newtonsoft.Json.JsonConvert.SerializeObject(resp.Cookies); resulting to the following json [ { "Comment": "", "CommentUri": null, "HttpOnly": false, "Discard": false, "Domain": "www.site.com", "Expired": true, "Expires": "1970-01-01T03:30:01+03:30", "Name": "version",...

Serializable class with ISerializable constructor

c#,serialization,deserialization,serializable
Is it possible to declare the class [Serializable], and yet add a constructor with the signature (SerializationInfo information, StreamingContext context) to do some specific task at the time of deserialization?

Reliable way to check if objects is serializable in JavaScript

javascript,json,serialization
Is there a known way or a library that already has a helper for assessing whether an object is serializable in JavaScript? I tried the following but it doesn't cover prototype properties so it provides false positives: _.isEqual(obj, JSON.parse(JSON.stringify(obj)) There's another lodash function that might get me closer to the...

WCF Service hosted in a Windows Service - Wrong / Expected Namespace

c#,xml,wcf,serialization,datacontractserializer
I have a WCF Service that I've installed that keeps throwing an unexpected namespace exception upon startup. The odd part is that it works just fine if I host it via IIS or in visual studio via the WCFSvcHost. I'm unable to find any namespace declaration in the designer when...

What is the difference between a lambda and a method reference at a runtime level

java,serialization,lambda,java-8
I've experienced a problem that was happening using a method reference but not with lambdas. That code was the following : (Comparator<ObjectNode> & Serializable) SOME_COMPARATOR::compare or, with lambda, (Comparator<ObjectNode> & Serializable) (a,b) -> SOME_COMPARATOR.compare(a,b) Semantically, it is strictly the same, but in practice it is different as in the first...

Read nested json objects that have been serialized via gson library

java,json,serialization,gson,deserialization
I am storing an object in shared preferences. To do this I am serializing the object using the gson library and a typeadapter before storing them. Here's what my object looks like in json: { "id": 0, "name": "Sensor 2D:D3:5C", "address": "00:07:80:2D:D3:5C", "device": { "mAddress": "00:07:80:2D:D3:5C" }, "temp": "31342e37" }...

Why does Java serialization take up so much space?

java,serialization
I tried serializing instances of Byte and Integer and was shocked by how much space they took up when they were received on the other end. Why is it that it only takes 4 bytes to make an Integer, but it takes up over 10 times that many bytes upon...

How to serialize object with List inside in C# using XElement?

c#,xml,serialization,xelement
I have object with members of different types like this: public class MyObject { public string Str1 = string.Empty; public MyEnums.Enum1 E1 = MyEnums.Enum1.Unknown; public bool Done = false; }; I have Dictionary of these objects: Dictionary<string, MyObject> MyObjectsDic = new Dictionary<string, MyObject>(); And serializer for it like this: public...

Invalid cast when passing serializable object to activity

java,android,serialization
I have a complex object (which includes further objects and hashmaps). All objects implement Serializable. In the first activity I do: public void secondActivity(MyObject o) { Intent intent = new Intent(this, SecondActivity.class); intent.putExtra("myobject", o); startActivity(intent); finish(); } Then, in the second activity I'm doing: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);...

NoClassDefFoundError with Kryo

java,serialization,classpath,kryo
I am looking for Kryo custom Serialization and De serialization example. How to check the the correctness of the Kryo read and write function. I have written some code to check, but it return exception. Any help would be appreciable. Thanks in advance. import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.KryoSerializable; import com.esotericsoftware.kryo.Serializer; import...

Serialize only specific attributes using Writes trait with unapply

json,scala,serialization,playframework
Lets imagine I have a case class like this: case class Product(ean: Long, name: String, description: String) and I want so serialize objects of this class to Json, I can implement the Writes trait like this: implicit val productWrites: Writes[Product] = ( (JsPath \ "ean").write[Long] and (JsPath \ "name").write[String] and...

serializing a list of KeyValuePair to XML

c#,xml,serialization
I am trying to serailize an Object into XML. Below is the XML format which I need. <parameters> <parameter> <key>Key1</key> <value>Value1</value> <key>Key2</key> <value>Value2</value> <key>Key3</key> <value>value3</value> </parameter> </parameters> Below is the Model I have created [Serializable] [XmlType("parameters")] public class parameters { public List<parameter<string,string>> parameter { get; set; } } [Serializable]...

Serialize data-attributes

jquery,arrays,serialization,multidimensional-array
I have a drag and drop system, and each dropped item receives three data-attributes. data-id data-order data-content Now I should put these attributes into a multidimensional array. It should look like this: data-order = "0" [data-id = "1", data-content = "blabla"]; data-order = "1" [data-id = "2", data-content = "another...

Coherence config default override path

java,serialization,override,weblogic12c,oracle-coherence
I've already spent more than 2 days trying to make this work without any result. The server is WebLogic 12c with embedded Coherence server. It is important to mention that I do not run Coherence in standalone mode, instead it starts automatically alongside the application server that has access to...

StringContent vs ObjectContent

c#,json,serialization,httpclient,dotnet-httpclient
I am using System.Net.Http's HttpClient to call a REST API with "POST" using the following code: using (HttpRequestMessage requestMessage = new HttpRequestMessage( HttpMethod.Post, new Uri(request)) { }) { response = await httpClient.PostAsync(request, objectContent); } The "objectContent" is currently this - objectContent = new ObjectContent(jsonContent.GetType(), jsonContent, new JsonMediaTypeFormatter()); I was wondering...

Partial deserialization of a huge binary file - Java

java,serialization
This is my first question to StackOverflow. Please let me know if the question is not clear and need any more details. I have a class which has three attributes like this: class SampleClass { long [] field1; float[] field2; float[] field3; } A huge SampleClass object is built(with about...

Xml serializing and deserializing with memory stream [duplicate]

c#,xml,serialization
This question already has an answer here: Root element is missing 4 answers I'm getting an error with the following code where it can't find a root element when it tries to deserialize the code: An exception of type 'System.InvalidOperationException' occurred in System.Xml.dll but was not handled in user...

How to transfer java .class from one machine to another machine through network?

java,serialization,mapreduce,rmi
So basically, I am trying to implement a MapReduce framework in java. Problem here is, I want slave nodes(machines) know user-defined map and reduce functions. At the beginning, only master node knows what use code is, because by default, users write code on master machine. However, slave nodes and master...

Save GoogleApiClient on Activity restart in Bundle

android,serialization,parcelable,google-cast
My application has a function of theme change (i.e. Activity is restarting). Is it possible to save somehow GoogleApiClient with its all callbacks state and parameters into Bundle in onSaveInstanceState() so that I don't need to rebuild it every time? I'm using Google Cast Api Client (for Chromecast devices). mApiClient...

JSON serialization using newtonsoft in C#

c#,json,serialization,json.net,jsonserializer
I have the following model structure. public class ReferenceData { public string Version { get; set; } public List<DataItem> Data { get; set; } } public class DataItem { public Dictionary<string, string> Item { get; set; } } In the dictionary i'm adding the key value pair and serializing with...

Prevent GSON from serializing JSON string

java,json,serialization,gson
I'm new to gson, and have newby question which I have not found an answer to, so please bear with me. StackOverflow and google were not my friend :( I have a java class "User", and one of its properties, "externalProfile" is a Java String containing already serialized JSON. When...

TypeError: object is not JSON serializable in DJango 1.8 Python 3.4

python,json,django,python-3.x,serialization
I'm using DJango 1.8 and Python 3.4 When the below view is being ran, Django throws Type Error - Object is not JSON Serializable Views.py from django.http import HttpRequest,HttpResponse from django.http import JsonResponse from json import dumps def get_stats(request): if request.method == "POST": srch_dropV = request.POST['srch_dropAJ'] else: srch_dropV = ''...

Writing a BufferedImage cache and save it to disk

java,caching,serialization,bufferedimage
I'm developing a java application in which I load some long lists containing images (downloaded from web), so I added a quick HashMap<String,BufferedImage> as a cache, to avoid redownloading the same image multiple times. This works fine and the application is way faster, but it would be nice to let...

WCF singleton service with multiple endpoints?

wcf,serialization,singleton,wcf-endpoint
I have a singleton wcf service (InstanceContextMode.Single) i.e MyService with multiple endpoints namely netmsmq and http. The call to netmsmq works fine but when I call it as : Binding bin = new BasicHttpBinding(); EndpointAddress end = new EndpointAddress("http://localhost/WcfService1/MyService.svc"); var obje = new ChannelFactory<IMyService>(bin, end); obje.Open(); var factory = obje.CreateChannel();...

Correct getters for non intrusive boost serialization C++

c++,serialization,boost,boost-serialization
I would like to provide getters of class A for my non-member serialize() function` since accessing from members is private. template<typename T> class A { public: A(const T& id) : m_id(id) {} T& getRef() { return m_id; } // not giving good results T getId() { return m_id; } //...

reconstruct python method with kwargs with marshal and types?

python,serialization,deserialization,marshalling,unmarshalling
I am using the marshal module to serialize some Python methods, and reconstruct them using types module (Is there an easy way to pickle a python function (or otherwise serialize its code)?). I am having trouble getting it to work with optional kwargs. E.g. import marshal import types def test_func(x,...

deserialize a list of Guid c#

c#,list,serialization,guid
Can anyone help me to deserialize this xml file into a list of Guid ? <?xml version="1.0" encoding="UTF-8"?> <content> <0>124179e5-82b9-c551-1e88-515ec3bbe4e3</0> <1>5c8246d3-5b9f-16bb-89dc-515ec4674170</1> <2>9d7f4701-81e3-3c90-c743-515ec9580852</2> <3>ea8d97bd-243b-b917-bc15-51764c2b2f34</3> </content> Thanks in advance....

Is it possible to serialize Map.keySet without copying the Set?

java,serialization
As we all know, KeySet of Map is not serializeable. But I have cases where I just want to send the KeySet of a Map wrapped in a custom Object over wire. So I have implemented the writeObject method to check for a serializable Set. My question now is, if...

problems when I serialize sparse_hash_map into file

c++,serialization
Here is my code to serialize sparse_hash_map(char *const, int) into file, notice the map.key type is char *const, which is required(if not, compiler reports no matched function found). That's where problems occurs, since I can't allocate memory to a variable of type char *const, how can I read data from...

What happens to type if I derive non-generic class from a generic class?

java,generics,serialization
Let us say, I have a usual POJO called Person. Now, an instance of ArrayList<Person> will have type ArrayList at runtime due to type erasure. If this instance undergoes serialization/deserialization through some library like Gson, the desirialized object is not ArrayList<Person> unless, of course, we specifically provide a type token....

Unable to extract values from object array, to which javascript array was deserialized

c#,arrays,object,serialization
var serializedArray = new JavaScriptSerializer().Deserialize<object[]>(filter); The content of the variable filter is [["Title","contains","foo"],"and",["Name","contains","foo"]]. Content of serializedArray is "object[3]","and","object[3]". Content of serializedArray[0] is object[3] which are "Title", "contains", "foo". serializedArray can be used with index operator, and foreach is applicable. But not for serializedArray[0]. Funny enough, both the serializedArray and serializedArray[0]...

Deserializing Json data to c# for use in GridView - Error Data source is an invalid type

c#,json,gridview,serialization,.net-4.5
I am relatively new to working with C# (v5.0) and Json data (Newtonsoft.Json v6.0) and am seeking assistance in resolving an error when attempting to populate a .Net 4.5 GridView control. My sample Json data as returned by a web service is: { PersonDetails: [ { Book: "10 ", FirstName:...

Remove '@class' in XStream for Java primitive types

java,serialization,restlet,xstream
I have this field in a POJO that is serialized into JSON: @XStreamAlias("tags") List<String> tags; My problem is that the output looks like this: "tags": [ { "@class": "linked-list", "string": [ "test", "test2" ] } ], In what way that the output would look like this: "tags": [ "test", "test2"...

Ruby Marshal.dump gives different results for what looks like the same thing

ruby,serialization,marshalling
I'm seeing slightly different results with Ruby's Marshal.dump depending on if I called .to_s on something or I typed in the characters. I'm really not clear on what's happening here: » Marshal.dump(1.to_s) => "\x04\bI\"\x061\x06:\x06EF" » Marshal.dump('1') => "\x04\bI\"\x061\x06:\x06ET" » 1.to_s == '1' => true So although it appears that 1.to_s...

Serialization error using a jdbc-message-channel

serialization,spring-integration
I'm using a channel backed by a jdbc-message-store but I'm having a serialization error when storing the message. The message payload is a simple String. Here's my config and stacktrace: <bean id="auditMessageStoreQueryProviderBean" class="org.springframework.integration.jdbc.store.channel.MySqlChannelMessageStoreQueryProvider" /> <bean id="auditMessageStore" class="org.springframework.integration.jdbc.store.JdbcChannelMessageStore"> <property name="dataSource" ref="auditMessageStoreDataSource" /> <property...

Serialization exception using C#

c#,serialization,deserialization
I am new to C# and am trying to write some information to a file. I got the program running properly when I have the Car class in the same .cs file, but when I remove this class into another .cs file in the project, I get the runtime error...

Why do I need to specify an xml namespace when I do serialization?

c#,asp.net,.net,wcf,serialization
I do not quite understand the reason why I need to specify an xml namespace for an object when I serialize the object to the wire. By default, the xml namespace for this object will be the CLR namespace of this object, this is enough for us to differentiate two...

ManyToMany Through Field Serialization

python,json,django,serialization,django-rest-framework
I am having problems serializing my items/orders with quantity. Results I am getting: { "id": 1, "_current_status": null, "orderitem_set": [ { "item_id": 2, "quantity": 5 }, { "item_id": 1, "quantity": 1 } ], "items": [ { "id": 2, "name": "Blue Shoe", "description": "Sweet blue shoe bro", "weight": "99.99", "price": "99.99"...

What elements does jQuery serialize affect?

jquery,serialization
I'm digging through the jquery production file and it doesn't seem that there's a definitive list of elements jquery will serialize. IE how does it know to serialize inputs and selects? I am curious because I have a common function to serialize my forms, that first does some checkbox value...

Json serialization issue when using Struts2-Json plugin

json,serialization,struts2,struts2-json-plugin
I have an action class with 3 properties. I am using Struts2-Json plugin to serialize the action class. I am able to serialize the String selectedCompany as per my expectations The problem The People ArrayList<Person> property is serialized with empty values. I don't seem to find where I have made...

Spark Task not serializable (Case Classes)

scala,hadoop,serialization,apache-spark,closures
Spark throws Task not serializable when I use case class or class/object that extends Serializable inside a closure. object WriteToHbase extends Serializable { def main(args: Array[String]) { val csvRows: RDD[Array[String] = ... val dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss") val usersRDD = csvRows.map(row => { new UserTable(row(0), row(1), row(2), row(9), row(10), row(11))...

Serialized data being displayed

php,html,forms,serialization
I need to make a config file for my application, but i stumbled upon a problem, i tried to solve it but couldn't find the problem, the code here works, except for one thing, whenever i submit the form, it will save the data, but when it reloads it will...

Java Deserialization Error

java,serialization
So for some reason stack overflow won't let me post more than 2 links so here is a link containing links: http://pastebin.com/FERUSH2P Hello, so I have no idea why but I am getting ClassNotFoundException when trying to deserialize a .bin file. I am serializing in one program and deserializing in...

Performance degradation of fast-serialization

java,performance,serialization
This question is particular to the Fast-Serialization library. https://github.com/RuedigerMoeller/fast-serialization I am using FSTLongOffheapMap (version 2.29) on windows 7, jdk 1.7 to store some objects. I tested the latency of storing an object and the 99.99 percentile comes to about 100 micros. This is excellent considering I ran it on windows...

Array unserialize issue returning null/false

php,arrays,serialization
I've got an array being returned in this format: a:1:{i:0;i:305;} I can't seem to unserialize() it to access the 305. Anyone have an idea on what I can do? Query in WordPress: $order_id = $wpdb->get_row("SELECT meta_value FROM wp_postmeta WHERE post_id=" . $t->object_id . " AND meta_key='wpc_inv_order_id"); I attempted to use:...

Boost serialization does not work between 32bit and 64bit machine. Any other serialization / compression library?

c++,serialization,boost,32bit-64bit,cereal
I am trying to use the boost library to serialize on 64bit machine and de-serialize on 32bit machine. However, it seems it does not work. (I use 1.57.0). If I run the following code boost::asio::streambuf buf; std::ostream os(&buf); boost::archive::binary_oarchive oa(os); printf("Buffer size %d\n",(int)buf.size()); The output of 32bit machine is 37...

EF6 Application Not Serializing Collection

c#,asp.net-mvc,entity-framework,asp.net-mvc-4,serialization
I am working through my first entity framework/MVC application, and am having an issue on the API side of the application. Here is the code [DataContract(IsReference=true)] [KnownType(typeof(Project.Models.StepByStep))] public class StepByStep { [DataMember] public int Id { get; set; } [Required] [DataMember] public string Name { get; set; } [Required] [DataMember]...

Is Java SerialVersionUid of 1L ok? Or does it need to be unique?

java,serialization,serialversionuid
I have two java classes which implement Serializable. I set both of them to have a serialVersionUid of 1L. A coworker said that all classes must have a unique serial version uid and that the jvm will treat classes as equal if they have the same serial version uid. I...

How to covert JSON field name to a Java compatible property name while doing Jackson de-serialisation?

java,json,serialization,jackson,deserialization
I have ServerDetails pojo class. package org.vo; import org.codehaus.jackson.annotate.JsonProperty; public class ServerDetails { private Integer serverId; private String server_url; public ServerDetails() { } public ServerDetails(Integer serverId, String server_url) { this.serverId = serverId; this.server_url = server_url; } @JsonProperty("server-id") public Integer getServerId() { return serverId; } public void setServerId(Integer serverId) { this.serverId...

How can I create a txt file that holds the contents of an array in JavaScript?

node.js,matlab,serialization,ar.drone
I have several arrays that contain data that I would like to export, each array to a txt file, in order to be analyzed using MATLAB. Let's say my array is: var xPosition = []; // some algorithm that adds content to xPosition // TODO: export array into a txt...

how to get object with retrofit library?

android,json,serialization,retrofit
i am first time trying to use retrofit library, and i got a problem. here is my JSON: { "id":"15", "email":"[email protected]", "phone":null, "password":"", "login":"", "userProfile":{ "lan_status":"", "name":"example", "sex":"0", "second_name":"", "date_of_birth":"0000-00-00 00:00:00" } } here is my retrofit code: String url = "https://example.com"; RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(url) .build(); mServerApi...

Python: Serializing/de-serializing huge amount of data

python,serialization
I have a (very large) dataset. Something in the order of 250,000 binary vectors, each of size 800. The dataset resides in a (.txt ascii coding) file, in 'compressed representation'. Meaning, every line in that file represents how a vector looks, rather than 800 characters of zeroes and ones. For...

Jackson How to retrieve parent bean in a custom Serializer/Deserializer

java,json,serialization,jackson
In a custom serializer/deserializer, is there a way to retrieve the parent bean of the field ? For example : public class Foo { @JsonSerialize(using = MyCustomSerializer.class) public Bar bar; } public class Bar { } public class MyCustomSerializer extends JsonSerializer<Bar> { @Override public void serialize(Bar value, JsonGenerator jgen, SerializerProvider...