Menu
  • HOME
  • TAGS

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

java,json,serialization,jackson

If you are using Jackson 2.5, it is possible to access parent object via JsonGenerator.getCurrentValue(). Or, further up the hierarchy, going via getOutputContext() (which has getParent() as well as getCurrentValue() method). This is also available through JsonParser for custom deserializer.

Save GoogleApiClient on Activity restart in Bundle

android,serialization,parcelable,google-cast

You should maintain the googleapiclient connection inside a service rather that in an activity which can get killed during configuration changes. Your theme change has no relation to apiclient object. So it is a good practice if you decouple your UI and core logic to avoid such issues.

Include a method when object is serialized in JMS

symfony2,serialization,jmsserializerbundle

You need to set @VirtualProperty and @SerializedName. use JMS\Serializer\Annotation\VirtualProperty; use JMS\Serializer\Annotation\SerializedName; class Person { .... .... .... /** * @VirtualProperty * @SerializedName("foo") */ public function getFoo(){ return $this->id + 1; } .... .... .... } You can read more about it here: http://jmsyst.com/libs/serializer/master/reference/annotations Pay attention that this only works for...

Upgrade Compatibility of Boost Serialization with binary archives armv7 to arm64

c++,serialization,boost,boost-serialization,arm64

If you need to keep user's data you're gonna have to reverse engineer your way out of hell. You could maybe cheat by having the old data sent to a server for transformation. For portable archives you can try the OES Portable Archive implementation. It is supposed to be a...

Serialization exception using C#

c#,serialization,deserialization

When the data.bin was first created the class type is stored along with the data. if you change the class's namespace, then the formatter is not able to find the class that was stored.

Saving FileSystemInfo Array to File

c#,arrays,xml,file,serialization

FileSystemInfo isn't serializable, because it is not a simple type. FileInfo isn't serializable, because it has no empty default constructor. So if you want to save that information, you have to build your own class with simple types, that wrap that the information from FileInfo or FileSystemInfo. [Serializable] public class...

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

java,json,serialization,jackson,deserialization

The issue has been resolved and full credit goes to both sotirios-delimanolis and staxman.Generally people like to find direct answer and not really like to going through the comments although the actual answer can be present among those comments. So this answer is dedicated for those kinds of users who...

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

django,serialization,foreign-keys,django-rest-framework

The issue is that you are passing the name of the related Destination object into the serializer, instead of passing the pk/id of the Destination object. So Django REST framework is seeing this and complaining, because it can't resolve LA into an object. It sounds like you may actually be...

Serializing a treenode like data structure

c#,serialization

Here you go. I hope it will be an answer on your question PUSH And here is the code var serializer = new XmlSerializer(typeof(MyClass)); using (var ms = new MemoryStream()) { var sw = new StreamWriter(ms); serializer.Serialize(sw, _class); sw.Flush(); ms.Position = 0; var sr = new StreamReader(ms); var myStr =...

Read nested json objects that have been serialized via gson library

java,json,serialization,gson,deserialization

Is there a reason to use a TypeAdapter instead of mapping directly the JSON into an object? For instance with: Gson gson = new Gson(); Info info = gson.fromJson(jsonString, Info.class) If you need to use the JsonReader, then you could consider using JsonToken by calling reader.peek(). You will then be...

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

c#,xml,wcf,serialization,datacontractserializer

I didn't know that because I was using a Windows Service as a host, the XML file was saved to /windows rather than the local directory. The invalid namespace was from an old XML file that still existed in /windows/syswow64.

Java Deserialization Error

java,serialization

Your code seems correct (except for a minor remark - it's better to put your "stream.close()" in "finally" clauses). The error clearly indicates that the reading side doesn't have class "AnimatedModelData" on its classpath. Your can verify it by calling Class.forName("core.ModelData.AnimatedModelData") on the reading side, even without reading the stream....

Error during deserializing XML

c#,xml,serialization,deserialization

Use the [XmlElement] attribute: [XmlElement(ElementName = "StyleProperties", Namespace="http://schemas.datacontract.org/2004/07/PPT_Styles_Tool")] public class StyleProperties { //... Also, if you use the XmlSerializer to serialize, then you should use the XmlSerializer to deserialize. Not the DataContractSerializer....

Serialize data-attributes

jquery,arrays,serialization,multidimensional-array

http://jsfiddle.net/hk120Lhq/1/ $(".send").click(function() { var data_array = new Array(); $(".dropped").each(function(){ var item = {}; item['data-order'] = $(this).data('order'); item['data-id'] = $(this).data('id'); item['data-content'] = $(this).data('content'); data_array.push(item); }); var serialized = JSON.stringify(data_array); $("#result").text(serialized); }); So .each is the same as the loop you are trying to do. I'm not sure what you were doing...

POJOs to byte array vs POJOs to json

java,json,serialization

Serialize data means convert them to a sequence of bytes. This sequence can be interpreted as a sequence of readable chars as happens in json, xml, yaml and so on. The same sequence can be also a sequence of binary data that is not human readable. There are pro and...

What elements does jQuery serialize affect?

jquery,serialization

Serialized Elements jQuery currently (1.11.3) checks for input, select, textarea, and keygen elements. serialize.js line 13: rsubmittable = /^(?:input|select|textarea|keygen)/i; This gets used on lines 93-100 when filtering which elements to serialize: .filter(function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery(...

Error when serialize List

c#,serialization,windows-runtime,windows-phone-8.1

You must serialize/deserialize the list yourself, for example: string Serialize(List<string> list) { StringBuilder result = new StringBuilder(); foreach (string s in list) { result.AppendFormat("{0}{1}", result.Length > 0 ? "," : "", s); } return result.ToString(); } List<string> Deserialize(string s) { return new List<string>(s.Split(',')); } If your strings might contain commas,...

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

java,serialization,serialversionuid

The class name is part of the serialized representation of an object. The serialVersionUID is only used for versioning the classes. So 1L is a valid value. Note that if you don't plan to maintain the compatibility of serialization while evolving the class, serialVersionUID is useless, and you can just...

WCF singleton service with multiple endpoints?

wcf,serialization,singleton,wcf-endpoint

Yes, a wcf singleton service can have multiple endpoints. The problem was solved by using [ServiceKnownType(typeof(MyService1))] over the method declaration in IMyService interface. Like, [ServiceKnownType(typeof(MyService1))] public void MethodCall(IMyService1 obj); It was a serialization issue....

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

c#,arrays,object,serialization

var serializedArray = new JavaScriptSerializer().Deserialize<object[]>(filter); foreach (var item in serializedArray) { if (item is string) { var element = item; } else foreach (var innerItem in (object[])item) { var element = innerItem; } } ...

Serializable class with ISerializable constructor

c#,serialization,deserialization,serializable

You can either inherit ISerializable or just add a couple custom methods to your class that are called during serialization/deserialization. These methods are decorated with special attributes that tell the serializer to call them: OnDeserializedAttribute OnDeserializingAttribute OnSerializedAttribute OnSerializingAttribute MSDN has a great tutorial (which I don't need to duplicate here)...

Why serialization is not required for InProc session mode

c#,asp.net,asp.net-mvc,session,serialization

Using InProc sessions, the data is not "stored" anywhere, it just stays in memory. This way no serialization is needed. For the other methods the data does need to be written to somewhere (state server, sql server) and needs to be converted to a stream of bytes (and back again)....

Serialize XML into CSharp class

c#,json,xml,visual-studio,serialization

Probably something wrong with your ResultSet class, this works fine for me: [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)] public partial class ResultSet { private ResultSetResult[] resultField; [System.Xml.Serialization.XmlElementAttribute("Result")] public ResultSetResult[] Result { get { return this.resultField; } set { this.resultField = value; } } } [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]...

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

java,serialization

There's really no way to "optimally detect when a serialization structure changes" for one rather important reason: Serialization breaks encapsulation. When you implement Serializable, all the private and package-private fields and members of a class become part of that class's exported API. From the moment that a class is published...

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

java,serialization

If it is about few fields then you can always mark them as transient. But if you need more controlled logic in your searilization then Externalizable is the answer. You can override the serialization and deserilization process by implementing methods writeExternal and readExternal methods of Externalizable interface. Here is small...

ManyToMany Through Field Serialization

python,json,django,serialization,django-rest-framework

By changing the OrderSerializer items field to be an OrderItemField I was able to get back to root Order by using self.root.instance and then using that in conjuction with the value, which is an Item instance, build a query to find the OrderItem object to get the quantity. Then I...

Produce different serialized JSON for a given class in different scenarios

c#,json,serialization,asp.net-mvc-5,json.net

I finally went with a mix of Wrapper classes and the methodology suggested by Raphaël Althaus: use Wrappers where some amount of sophistication may be required and use Raphaël's suggestion when simplicity will do. Here's how I am using wrappers (intentionally left out null checks): public class Entity1View1 { protected...

Casting error from deserialized json in c# using newton json

c#,json,serialization,casting,json.net

Because the type of deserializedData["key"] is Int64 (you'll see when you debug). You can't cast Int64 to int (Int32) . what you can do: int value = System.Convert.ToInt32(deserializedData["key"]); ...

Invalid cast when passing serializable object to activity

java,android,serialization

You are doing all fine, so I think that can be: your are sending to secondActivity method an incorrect object (like ArrayList instead of correct MyObject) Please look if you are using this key "myobject" in other part of the code and setting other object in putExtra. verify MyObject class...

Reliable way to check if objects is serializable in JavaScript

javascript,json,serialization

In the end I created my own method that leverages Underscore/Lodash's _.isPlainObject. My function ended up similar to what @bardzusny proposed, but I'm posting mine as well since I prefer the simplicity/clarity. Feel free to outline pros/cons. var _ = require('lodash'); exports.isSerializable = function(obj) { if (_.isUndefined(obj) || _.isNull(obj) ||...

Value Object vs Data Transfer Object

java,design-patterns,serialization,domain-driven-design,data-transfer-objects

Objects are made Serializable to be able to be transferred. It allows to convert Object to bytes and then bytes to Object. Note that usually DTO are made lighter (since travelling to client) than your Domain Objects that usually have a lot of attributes made for Business processing only. So...

deserialize a list of Guid c#

c#,list,serialization,guid

Your file isn't a valid XML file. According to the W3C website, node identifiers cannot start with digits. Not respecting the actual node identifiers, he common way to read your list would be: List<Guid> guids = new List<Guid>(); XmlDocument doc = new XmlDocument(); doc.Load(@"guids.xml"); foreach(XmlNode guidNode in doc["content"].ChildNodes) { guids.Add(Guid.Parse(guidNode.Name));...

Rails serialize not storing correctly

ruby-on-rails,json,serialization,stripe-payments,stripe-connect

When you ask Rails to serialize an attribute on a model, it will default to storing the object as YAML string. You can ask Rails to serialize differently, as you have noticed by providing a class to do the serialization e.g serialize :stripe_account_status, JSON The reason why this isn't working...

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

java,generics,serialization

Will the type information be preserved here? Yes; for example, this: final ParameterizedType superTypeOfPersons = (ParameterizedType) Persons.class.getGenericSuperclass(); System.out.println(superTypeOfPersons.getActualTypeArguments()[0].getSimpleName()); will print Person. Is deserialization mechanism able to infer that the type is indeed ArrayList<Person> and not raw type ArrayList? It potentially could do so, but that doesn't necessarily mean that...

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

c#,asp.net,.net,wcf,serialization

By default, the xml namespace for this object will be the CLR namespace of this object Is not great for interoperability with other software. The default is considered a develop-time stub. When you develop a separate Client and Server, only one could rely on this default. It is a...

Serialize/Deserialize class containing byte array property into XML

c#,.net,xml,serialization,.net-4.0

As you've noticed, there are lots of characters that may not be present in an XML document. These can be included in your data, however, using the proper escape sequence. The default settings of the XmlTextReader cause it to mishandle this -- I think it interprets the escape sequences prematurely,...

Coherence config default override path

java,serialization,override,weblogic12c,oracle-coherence

Instead of editing files inside of your Oracle_Home, try the following inside of the weblogic admin console: Login to admin console Servers link -> Server Name Click the Server Start tab Edit the Arguments: text box and add in -Dtangosol.pof.config=MyPOF.xml You can also change the classpath, Class Path: box, here...

Remove '@class' in XStream for Java primitive types

java,serialization,restlet,xstream

The solution is to add @XStreamImplicit annotation: @XStreamImplicit(itemFieldName="tags") List<String> tags; ...

NoClassDefFoundError with Kryo

java,serialization,classpath,kryo

Thanks for the responses. I somehow managed to correct the exception. After including "objenesis-1.2.jar" into the build path the code works fine.

problems when I serialize sparse_hash_map into file

c++,serialization

Answering the OP's question about char * being really that bad first. char * massively increases your workload when compared to std::string. First, no need for malloc and free (you aren't doing the free by the way). The sizing and resizing is done for you. In fact, all of the...

how to get object with retrofit library?

android,json,serialization,retrofit

public class GetUserProfileInfo { @SerializedName("id") public int mUserId; @SerializedName("email") public String mUserEmail; @SerializedName("phone") public String mUserPhone; @SerializedName("password") public String mUserPassword; @SerializedName("login") public String mUserLogin; @SerializedName("userProfile") public GetUserProfileInfo_2 userProfile; } ...

reconstruct python method with kwargs with marshal and types?

python,serialization,deserialization,marshalling,unmarshalling

After some more searching I discovered the dill package, which allows you to pickle more things than cPickle (the reason I was using marshal). When you directly reconstruct a serialized function (not using the func_code), you avoid this keyword issue I was having.

Need help converting JSON to C# Objects

c#,asp.net,json,object,serialization

This property: public Participants players { get; set; } doesn't correspond with the key participantFrames in the JSON string. You'll have to change the property name, or add the attribute [JsonProperty("participantFrames")] to it. Also, the class Event_Position is not used at the moment, nor do I see any occurrence in...

JSON serialization using newtonsoft in C#

c#,json,serialization,json.net,jsonserializer

You do not need nested generic collections if you use Json.NET 5.0 release 5 or later version. You can use JsonExtensionDataAttribute so that Item dictionary's keys and values will be serialized as a part of parent object. public class ReferenceData { public string version { get; set; } public List<DataItem>...

Need help to understand deserialization with ArrayList in Java

java,serialization,arraylist,casting,deserialization

It tells your that the compiler is unable to guarantee you that the cast would be successful in runtime - it may produce ClassCastException. Usually you are able to check type previously with instanceof to prevent this warning, e.g.: if (x instanceof ArrayList) { ArrayList y = (ArrayList) x; //...

Correct getters for non intrusive boost serialization C++

c++,serialization,boost,boost-serialization

You can use good old-fashioned friends: Live On Coliru template <typename T> class A { public: A(const T &id) : m_id(id) {} private: template <typename Ar, typename U> friend void boost::serialization::serialize(Ar&,A<U>&,const unsigned); T m_id; }; namespace boost { namespace serialization { template <class Archive, typename T> void serialize(Archive &ar,...

Deserializing arrays with protostuff

java,json,serialization,deserialization,protostuff

Protostuff uses special schema for serializing arrays - it puts array size to a serialized form for performance reasons. You should change field type of tags to List: private List<String> tags; Lists are serialized directly into a JSON array: {"id":1,"price":1.2,"name":"alex","tags":["tag1","tag2","tag2"]} ...

Why does Java serialization take up so much space?

java,serialization

Though Radiodef has clarified why the size of the serialized object is huge, i would like to make another point here so we don't forget the optimization present in the underlying java's serialization algorithm (almost in all algorithms). When you write another Integer object (or any object which is already...

Serialise nested list or alternatives

c#,list,serialization,nested

You need to rewind the stream and clear the previous data between reading and writing: static void saveFunction(List<int> data, string name) { using (Stream stream = File.Open(name + ".bin", FileMode.OpenOrCreate)) { BinaryFormatter bin = new BinaryFormatter(); if (stream.Length == 0) { var List = new List<List<int>>(); List.Add(data); bin.Serialize(stream, List); }...

Array unserialize issue returning null/false

php,arrays,serialization

Looking what is result of unserialize $str = 'a:1:{i:0;i:305;}'; var_dump($a = unserialize($str)); array(1) { [0]=> int(305) } So take it by$a[0];...

Deserialize a json serialized CookieCollection

c#,serialization,json.net,json-deserialization,httpcookiecollection

JSON.NET doesn't support deserializing non-generic IEnumerables. CookieCollection implements IEnumerable and ICollection, but not IEnumerable<Cookie>. When JSON.NET goes to deserialize the collection, it doesn't know what to deserialize the individual items in the IEnumerable into. Contrast this with IList<Cookie> which has a generic type parameter. JSON.NET can determine what type each...

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

c#,xml,serialization,xelement

Rather than attempting to use reflection to manually serialize your MyObject class, you can use XmlSerializer to serialize your dictionary values directly to an XElement using the following methods, then include the result in the element tree you are building: public static class XObjectExtensions { public static XElement SerializeToXElement<T>(this IDictionary<string,...

EF6 Application Not Serializing Collection

c#,asp.net-mvc,entity-framework,asp.net-mvc-4,serialization

Make sure in your API calls you are including the child objects when retrieving the parent. There are certain situations where the child objects are not automatically included when using EF. Refer to the "Eager Loading" portion of this link. NOTE: It's called out in the article above, but I...

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

python,json,django,python-3.x,serialization

You have to serialize your student objects list, try something like this: from django.http import HttpRequest,HttpResponse from django.http import JsonResponse from json import dumps from django.core import serializers def get_stats(request): if request.method == "POST": srch_dropV = request.POST['srch_dropAJ'] else: srch_dropV = '' if(srch_dropV == 'Green'): students = GreenBased.objects.all() if(srch_dropV == 'Yellow'):...

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

java,serialization

One reason i could think of is the concurrent modification to the Map. Say what happens when there is a delete after the following statement is executed? stream.writeInt(map.size()); Say initially when the Map size is retrieved, the number of elements present in the map is 2, but say some other...

Performance degradation of fast-serialization

java,performance,serialization

Hi (i am author of FST): I think the test is flawed: When running your sync (no queues + thread context switches) test in a loop (=proper warmup) I get a Mean of 0.7 micros and Max outlier of 14 micros (doubled number of elements in map though) storing a...

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

java,serialization,deserialization,thrift

Exchange serialized entities as binary data That's a simple three-step process: serialize the data, e.g. into a ByteBuffer or the like send that data through the Thrift interface by means of binary deserialize the bytes received into Java entities The service could be as simple as service MyCoolService { binary...

Serialization error using a jdbc-message-channel

serialization,spring-integration

Spring Messaging (and hence Spring Integration) only looks at top level header values for non-serializable headers (and removes them before serializing - which means such headers are lost). for (Map.Entry<String, Object> entry : this.headers.entrySet()) { if (!(entry.getValue() instanceof Serializable)) { keysToRemove.add(entry.getKey()); } } Scanning the entire header tree (i.e. examine...

Non-intruisive Boost serialization of labelled enums C++

c++,serialization,boost

I think you need to separate loading from saving. This compiles, I wonder it it is worth the game... struct fruit_serializer { e_fruit &a_; fruit_serializer(e_fruit &a) : a_(a) {} template<class Archive> void save(Archive & ar, const unsigned int version) const { std::string label = labels[static_cast<int>(a_)]; ar & boost::serialization::make_nvp("label", label); }...

XML writer with repeating elements in node.js

javascript,json,xml,node.js,serialization

To whom it may concern, I ended up with "xml": https://www.npmjs.com/package/xml It only requires changing the input into: var objectToSerialize = [{ SomeElement: [ { Data: 3 }, { Data: 5 }, { Data: 2 } ] }]; ...

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

python,django,rest,serialization

According to the django rest framework documentation, this is how you can define your serializer class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style') As you can see, the model is mentioned in the Meta tags. This is called the ModelSerializer...

Using Gson to serialize strings with \n in them

java,serialization,gson

I am guessing that the gsonOutput has escaped the new line so if you change the line final String gsonOutput = new Gson().toJson(map); to (to unescape it): final String gsonOutput = new Gson().toJson(map).replace("\\n", "\n"); you will get the output gsonOutput:{"x":"First_Line Want_This_To_Be_Printed_In_Next_Line_With_A_Tab_Before_It"} toStringOutput:{x=First_Line Want_This_To_Be_Printed_In_Next_Line_With_A_Tab_Before_It} There probably is a better way of...

ForeignKey ListField serialization on rest_framework with django-nonrel

django,mongodb,serialization,django-rest-framework,django-nonrel

The issue here is that you are passing a string (unicode type) to DRF but you are expecting DRF to turn it into a nested representation. Without anything extra, DRF is not possible to do this, as it's way out of the general scope that it tries to maintain. Django...

Jersey serializing null values to json : How to skip

java,json,spring,serialization,jersey-2.0

Assuming, you are using Jackson for serialization, you can use the @JsonInclude(Include.NON_NULL) to your class to exclude the null values.

While Conditions for Deserializing Multiple Objects in Java

java,serialization

readObject() doesn't return null at end of stream. It can do that any time. It returns null if you wrote a null. So you can't use that. available() == 0 is not a test for end of stream: see the Javadoc. So you can't use that. readObject() throws EOFException...

StringContent vs ObjectContent

c#,json,serialization,httpclient,dotnet-httpclient

I was wondering what difference it makes if this was a StringContent rather than an ObjectContent like this? In your example there won't be any difference. ObjectContent simply allows a "wider" range of types to be sent via HttpClient, while StringContent is narrower for string values only, such as...

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

node.js,matlab,serialization,ar.drone

The solution you found works, but here's how I'd have done it: var fs = require('fs'); var xPosition = [1,2,3]; // Generate this var fileName = './positions/x_n.txt'; fs.writeFileSync(fileName, xPosition.join('\n')); This uses node's synchronous file writing capability, which is ideal for your purposes. You don't have to open or close file...

C# Protobuf .NET Using Preexisting Byte Array

c#,networking,serialization,protobuf-net,objectpool

Use a memory stream using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Serialization; using System.IO; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Person person = new Person(); XmlSerializer serializer = new XmlSerializer(typeof(Person)); MemoryStream stream = new MemoryStream(); serializer.Serialize(stream, person); } } public class...

Deserializing Json String into multiple Object types

c#,json,serialization,json.net

As @YeldarKurmangaliyev already said, your json has two different objects, I think you can do something like this: var j = JArray.Parse(data); TeamsList = JsonConvert.DeserializeObject<List<Team>>(j[1].ToString()); MobileUsersList = JsonConvert.DeserializeObject<List<User>>(j[2].ToString()); ...

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

javascript,c#,json,parsing,serialization

One possibility is to deserialize into a dynamic object and convert from that to your strongly-typed object. Like so: var dict = new JavaScriptSerializer().Deserialize<dynamic>(responseText); The resulting dict object is a dictionary, with each property represented as a name-value pair in the dictionary. Nested objects, such as roster and its contained...

Python: Serializing/de-serializing huge amount of data

python,serialization

If you were to store a bit for each value in your data, you'd end up with a 25MB file; so your "compression" scheme is actually making your file bigger. The only advantage of your current scheme is that you get to store your data in ascii. Calculation: 250.000 *...

Prevent GSON from serializing JSON string

java,json,serialization,gson

As stated by Alexis C: store the externalProfile as a JsonObject first: new Gson().fromJson(externalProfile, JsonObject.class)); And let gson serialize this again when outputting the User object. Will produce exactly the same JSON! ...

Serialization - not working

java,serialization

Based on the linked answer, the problem most likely lies in the code you aren't showing us. When you serialize your MyClass object, you are probably doing something like this: MyClass hl; String base64String = Serialization.toString(hl.toString()); However you should be calling it like this: MyClass hl; String base64String = Serialization.toString(hl);...

Partial deserialization of a huge binary file - Java

java,serialization

Forget using the Java serialization API - it's only designed to deserialize everything. If you have no control over how the serialized file is generated, then you should consider parsing the serialized file yourself and extracting the necessary parts - it's not really that hard. The Java serialization format is...

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

c#,json,gridview,serialization,.net-4.5

You're binding the container object, not the list itself. Change it to: GridView1.DataSource = personDetail.PersonDetails; And it should work....

Serialized data being displayed

php,html,forms,serialization

You have a mistake on this line : $file = fopen("config.php", "w");, this is config.txt and not config.php.

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

java,serialization,apache-spark

The gson reference is 'pulling' the outer class into the scope of the closure, taking its full object graph with it. In this case, create the gson object within the closure: public SupplierDTO call(String str) throws Exception { Gson gson = Gson(); return gson.fromJson(str, SupplierDTO.class); } You can also declare...

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

java,serialization,lambda,java-8

Getting Started To investigate this we start with the following class: import java.io.Serializable; import java.util.Comparator; public final class Generic { // Bad implementation, only used as an example. public static final Comparator<Integer> COMPARATOR = (a, b) -> (a > b) ? 1 : -1; public static Comparator<Integer> reference() { return...

Xml serializing and deserializing with memory stream [duplicate]

c#,xml,serialization

After serialization, the MemoryStream's position is > 0. You need to reset it before reading from it. memStream.Position = 0; ...

Serializing into JSON using MemoryStream,while adding newlines C#

c#,json,serialization

Ok, so if you want to do that just add this code answered in this question. question here...

Gson not deserializing JSON data

java,json,serialization,gson

Your JSON (which you get from Yahoo) is very complex. So it can not be easily mapped to simple POJO (but you still can write huge POJO that contains fields for all corresponding nested JSON elements). But it is possible to parse and extract specific elements from JSON. The code:...

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

java,serialization

Yes, One way to do is to serialize each objects individually without copying into a new set, private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException { Iterator itr = testSet.iterator(); if (testSet.getClass().equals(TM_KS_CLASS)) { stream.writeBoolean(true); } else { stream.writeBoolean(false); } stream.writeInt(testSet.size()); while(itr.hasNext()) { stream.writeObject(itr.next()); } stream.writeObject(justSomeOtherFieldToSerialize); } You need to have corresponding readObject...

Weirdness with Spark serialization

java,serialization,lambda,apache-spark

My question was not clearly expliciting why I was so baffled (about Kryo registering code not being executed), so I edited it to reflect it. I have figured out that Spark uses two different serializers : one for serializing the tasks from the master to the slaves, called closureSerializer in...

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

c++,serialization,boost,32bit-64bit,cereal

It does work. It just doesn't create compatible archives. If you want that you should look at the archive implementation that EOS made: EOS Portable Archive You can drop-in replace Boost's binary_[io]archive with it. No need to change anything else. PS. Of course, spell out your types in an architecture-independent...

Writing a BufferedImage cache and save it to disk

java,caching,serialization,bufferedimage

The error occurs because ImageIO.read(...) doesn't read all the data that was written using ImageIO.write(...). You can write the image to the ObjectOutputStread as a byte[]. For example: private static void writeCache(ObjectOutputStream oos, HashMap<String, BufferedImage> data) throws IOException { // Number of saved elements oos.writeInt(data.size()); // Let's write (url, image)...

core difference between set and serialized in cakephp 3.0?

serialization,cakephp-3.0

The _serialize key is a special view variable that indicates which other view variable(s) should be serialized when using a data view. This lets you skip defining template files for your controller actions if you don’t need to do any custom formatting before your data is converted into json/xml....

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

ruby,serialization,marshalling

Marshal.load("\x04\bI\"\x061\x06:\x06EF").encoding # => #<Encoding:US-ASCII> Marshal.load("\x04\bI\"\x061\x06:\x06ET").encoding # => #<Encoding:UTF-8> By default, 1.to_s.encoding is not the same as '1'.encoding. However, both strings are in 7-bit ASCII range, so they are comparable, and '1' == 1.to_s will be able to give you the result true, after some internal magic. But they are not...

Spark Task not serializable (Case Classes)

scala,hadoop,serialization,apache-spark,closures

It was the dateFormatter, I placed it inside the partition loop and it works now. usersRDD.foreachPartition(part => { val id = userRow.id val dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss") val date1 = dateFormatter.parseDateTime(userRow.date1) }) ...

Cheapest marker in java serialization?

java,serialization

The simplest way to mark a null is to use a null. oos.writeObject(null); You can mark with a boolean but writeObject(true) uses more space than just passing a null. if (node.item == null) { oos.writeByte(0); } else { oos.writeByte(1); oos.writeObject(note.item); } // to read Item item = ois.readByte() == 0...

Python - Load multiple Pickle objects into a single dictionary

python,serialization,pickle

my_dict_final = {} # Create an empty dictionary with open('pickle_file1', 'rb') as f: my_dict_final.update(pickle.load(f)) # Update contents of file1 to the dictionary with open('pickle_file2', 'rb') as f: my_dict_final.update(pickle.load(f)) # Update contents of file2 to the dictionary print my_dict_final ...

Serialize byte array in JSON.NET without $type

c#,json,serialization,json.net

One way to fix this would be to use a custom converter for byte[]: public class ByteArrayConverter : JsonConverter { public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer) { string base64String...