String-Object converter - java

I want a method that can convert an object (with a few parameters String or int) in a String, and more importantly, convert that String back in an object. Do you know any way to develop a converter for this purpose?
The problem is that the object is a DTO used by other developpers so I can't modify the toString() method. Thus I created my own method toString, but I don't know how can I reliably make a converter working both ways. I thought about several solutions (storing the objects in a map, etc), but they all seem unclear to read/understand. Is there any usual way to do it that every experienced programmers would understand in a blink of an eye what it does?
EDIT: Well, I know serialization, but my question wasn't clear, I'm sorry. The fact is that I want to display the objects in a ListView (JavaFX), to make them readable, like String "N°:xxxx; Version : 1", serialized objects aren't really esthetic nor readable.
So my final solution is something more like:
listView.setCellFactory(new Callback<ListView<ProductDto>, ListCell<ProductDto>>() {
#Override
public ListCell<ProductDto> call(final ListView<ProductDto> productDtoListView) {
return new ListCell<ProductDto>(){
#Override
protected void updateItem(final ProductDto productDto, final boolean b) {
if(productDto!=null){
setText(fromProductDtoToString(productDto));
}
}
};
}
});
This way, I store the objects themselves in the ListView, and can still display a fairly esthetic String representing the object.
Thanks for your time.
Fabien

You can for example use Jackson to convert object to JSON and vice versa. Check this article How To Convert Java Object To / From JSON
If you want, you can use XML binding too.
In general, there are number of serialization libraries/approaches:
XStream (for XML but not for JSON)
Jackson (for JSON)
Jackson xml module (faster than XStream)
Kryo (a fast, compact binary serialization format)
Smile (a binary format that comes with Jackson 1.6 and later).
Java Object Serialization.
SimpleXML seems solid, runs at 2x the speed of XStream, but requires more configuration effort
YamlBeans
SnakeYAML
Jackson JSON, Kryo, and Jackson Smile are all significantly faster than good old Java Object Serialization, by about 3x to 4.5x. XStream is on the slow side.

Related

Is JSON parsing or String parsing more expensive in Java?

I'm trying to dynamically parse a lot of data in Java. In other words I have tons of different types of data so I am putting them in a String or a JSON String (via GSON) instead of doing:
switch(data){
case instanceof Class1:
Class1 data = gson.fromJson(jsonString);
//Do Stuff for class 1 layout
case instanceof Class2:
Class2 data = gson.fromJson(jsonString);
etc.
So instead of doing this for 80 or so classes (which more may be added/removed/changed at any given time) I am planning to put the data in either a String or Json String and parse out the values (depth first).
I am on a low end PC (single core Atom processor) and am trying to reduce the amount of taxing I put on the CPU, so determining which would be faster... regex string manipulation with splits or using a recursive JSON parser.
Let us discuss both the cases you have mentioned here:
CASE 1:
Creating instances for each and every json input using gson (mapped to a Class)
and
CASE 2: Create a Document (or similar type object) itself and try accessing data from there.
For Case 2, you don't need to write a parser yourself: there are parsers already available.
I'll just write down a jackson example here (There must be similar stuff available with gson as well):
String myJson = "{ \"type\" : \"foo\", \"class\" : 3 }";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode node = objectMapper.readValue(myJson, JsonNode.class);
JsonNode type = node.get("type");
System.out.println(type.asText());
As per my experience, the performance difference hasn't been much in both these cases as the libraries handle the parsing quite efficiently but if you have a lot of different types of JSON, then it doesn't make any sense to create POJOs out of each and every JSON (So much mapping !!).
I have personally not worked with gson because of performance reasons like this but you can create what's called an ObjectMapper using jackson and use it quite efficiently. I assume there should be similar thing in gson as well.
The only downside would be that every field will now be accessible through a string input which might make your code a bit unreadable.
EDIT:
If you really wish to iterate through all the fields of the json, you'll have to do DFS ultimately, but parsing can still be avoided by using the fields method of the JsonNode.
root.fields() will return with an iterator with the entries in it which can be then gracefully used as described in answer here.
Remember, similar stuff with different names will be available in gson too. :)

MessagePack Java serializing as array

Is it accepted behaviour that MessagePack official implementation in Java serializes public fields as Arrays?
In what universe is this "like JSON"?
My case:
I have a simple class like so:
#Message
public class MySuperClass(){
public int mySuperID; // let's say 4
public byte[] mySuperData; // let's say nothing
public String mySuperType; // let's say null
public String mySuperExtra; // let's say HI!
public MySuperClass(){}
// other constructors
}
And i'm simply serializing with
MessagePack msgpack = new MessagePack();
msgpack.write(mySuperInstance);
And sending that to a distant server written in NodeJS.
Node JS can easily unpack it, to
['HI!', �, 4, null]
Which means that MessagePack is nothing like JSON, because it parses Java objects as arrays and then only repopulates them alphabetically!
Does anyone have a solution that does not include mapping every object I have? (Also HashMap is not unpackable by Node, which means that messagePack is not cross-platform ,thus, repeating, noting like JSON)
Judging from my MessagePack experience, it usually treats objects as MessagePack maps.
It doesn't use any language specific constructs so it is cross - platform.
I think you may be having issues because of the library you are using. You should consider the official one. You can read more about it here. It is basically an extension for Jackson that let's serialise and deserialise Java objects directly to / from MessagePack and was working (at least when I had to use it).

Java serialization to string

I have the following declaration of the static type Object:
Integer typeId;
//Obtaining typeId
Object containerObject = ContainerObjectFactory.create(typeId);
The factory can produce different types of container objects, e.g. Date, Integer, BigDecimal and so forth.
Now, after creating the containerObejct I need to serialize it to an object of type String and store it into a database with hibernate. I'm not going to provide Object-relational mapping because it doesn't relate to the question directly.
Well, what I want to do is to serialize the containerObject depending on it runtime-type and desirialize it later with the type it was serialized. Is it ever possible? Could I use xml-serialization for those sakes?
There are numerous alternatives, and your question is quite broad. You could:
use the native Java serialisation, which is binary, and then Base64 encode it
use an XML serialisation library, such as XStream
use a JSON serialisation library, such as Gson
One key feature you mention is that the object type needs to be embedded in the serialised data. Native Java serialisation embeds the type in the data so this is a good candidate. This is a double-edged sword however, as this makes the data brittle - if at some time in the future you changed the fully qualified class name then you'd no longer be able to deserialise the object.
Gson, on the other hand, doesn't embed the type information, and so you'd have to store both the JSON and the object type in order to deserialise the object.
XML and JSON have advantages that they're a textual format, so even without deserialising it, you can use your human eyes to see what it is. Base64 encoded Java serialisation however, is an unintelligible blob of characters.
There are multiple ways, but you need custom serialization scheme, e.g.:
D|25.01.2015
I|12345
BD|123456.123452436
where the first part of the String represents the type and the second part represents the data. You can even use some binary serialization scheme for this.

Map from JSON to java object with different structure

I have a JSON string representing an object, and I want to put its information into a Java object B with a different structure. Currently the solution I am taking is creating a Java Object A with a structure identical to the JSON object, made the conversion from JSON to A using Jackson and later, made the mapping from A to B using Dozer with XML mappings. Is there anyway to avoid having the A objects?
Making it short, currently I have this:
JSON--Jackson-->A--Dozer(XML mappings)-->B
and I would like to achieve this
JSON--???-->B
You may know this already, but Jackson can use loosely structure types like Map, or JsonNode as target, so you can do, say:
JsonNode root = mapper.readTree(jsonSource);
Map<String,Object> asMap = mapper.readValue(jsonSource, Map.class);
and then construct your B. Jackson has only limited amount of structural conversions (simple unwrapping), by design, although there is extensive set of scalar conversions (non-structural conversions), so if you do need structural changes it may make sense to use a library that is focused on structural changes.

Internal working of GSON

I am working with GSON in my current project, i am amazed to see its power and was wondering how did it work internally. How can a GSON object change the any object into JSON and vice versa. I did read the google user guide but the internal working is not mentioned their. Can anyone explain. Also this question might not appeal some people but i am new to android programming and was exploring things. Although i used gson successfully. But i do like to know its working methodology. Can any one explain.
Thanks a lot.
Gson's internals are built on three core types:
JsonReader reads the elements in a JSON document from a stream.
JsonWriter writes the elements in a JSON document to a stream.
TypeAdapter converts a single JSON element to a single object, or vice versa.
One key pattern is that TypeAdapter is implemented recursively. For example, the TypeAdapter<FoodDelivery> may delegate to a TypeAdapter<Address> and a TypeAdapter<MenuItem>. The TypeAdapterFactory interface makes it easy to build type adapters for arbitrary types.
One other key pattern is that Gson includes some awesome type adapters built-in by default. There's type adapters for primitives, strings, collections. Plus a special type adapter that takes an arbitrary Java class and converts it to a JSON object field-by-field.
I suggest that you do not perform recreation of objects and not force GSON except where it is needed. IMO, you have to use GSON anywhere where you have REST service, but GSON is more slower than java collections (ArrayList or HashMap or any other ...) and you will decrease app performances if you continue to use GSON everywhere.
Second reason is that when you perform object recreation, this is done in phone memory, and just for example, I had a problem with JSON (GSON) object which was exposed over service because it was 35-40MB and object creation uses over 70MB of RAM. There I had OutOfMemoryException, MemoryExhaustedException and more problems this kind.
If this limitations are not interested for you (you don't have large objects, or high speed is not required), then proceed to convert objects to GSON.

Categories