JSON, XML or String concatenation - java

I am doing a new application where I want to choose which protocol to use in it. I tried the String concatenation and the XML before, but never tried the JSON Object. Well Which one of those three is better in terms of performance? I am aware that XML is way much better than string concatenation. So what to use? XML or JSON? Or maybe a new technology that I am not aware of?
Thanks in advance
I am aware that XML is way much better than string concatenation. Well in this I mean that in String concatenation, I am adding different values and splitters to a string and then looping to find the spliters on the device. like in the example:
String toSend = "test1////test2////test3////test4////test5";
Here the splitter is "////" and I am sending 5 values. Getting these 5 values will be much more slower than XML in case of thousands of values.

It depends. :)
Well, actually I think a properly written code to split a string will be more fast than an XML/JSON parser, however XML/JSON parsers are reliable in terms of returning exactly the same data structure. For instance, how would you handle a case when your data itself includes splitters? If such case is impossible under your business logic, then you may just go with string joining/splitting. Otherwise it is better not to reinvent the wheel and just use XML/JSON (JSON is more lightweight).

It depends on the kind of Objects you will be exchanging.
It also depends on the way you will request and use you objects.
If you want ot provide a REST service that exposes simples Objects will be accessible directly by as Javascript GUI. I would also go for JSON. But no hand-made String concatenation to build JSON. You can use a lib.
But I you plan to exchange more complex data, between various Java based "services". I would probably go for XML. Especially if you can first write the XSD that defines you XML objects. You will be able to generate Java class and let JAXB do the marshalling/unmarshalling boring stuff.

I would choose JSON, it's very portable and lightweight (lighter than XML).

Related

JSON-to-JSON transformation: possible approaches

Sometimes there’s a need to perform a same-format transformation from one structure into another.
Now before you start with the implementation, you first need the theoretical basis. therefore my question to you is what possible approaches for the transformation are possible for JSON to JSON?
If you are talking about a JSON string: convert into a HashMap, do what you have to do then convert back to JSON. You can use a library such as JSON.simple
https://mkyong.com/java/json-simple-example-read-and-write-json/

Should I use XML Parser to modify XML template or convert to String and then modify?

I'm working on a project which requires me to insert values into a predefined XML template. Till now I have been using the StringBuilder class to convert the XML file into a string and make the required changes. Now, I wanted to know whether using an XML Parser like DOM,JDOM, SAX etc would be more efficient compared to the alternative way I'm using.
Since there are no implementation issues, I don't think any piece of code needs to be shared.
Please see this it may help you:
https://www.mkyong.com/java/how-to-modify-xml-file-in-java-dom-parser/
Modifying an XML document by string replacements in general is a bad practice as you can accidentally make your XML invalid, so for your task I would rather use simple XSL transformation.

How to convert thrift objects to readable string and convert it back?

Sometimes, we need to create some thrift objects in unit tests. We can do it by manually create object using Java code, like:
MyObj myObj = new MyObj();
myObj.setName("???");
myObj.setAge(111);
But which is not convenient. I'm looking for a way to create objects with some readable text.
We can convert thrift objects to JSON with TSimpleJSONProtocol, and get very readable JSON string, like:
{ "name": "???", "age": 111 }
But the problem is TSimpleJSONProtocol is write only, thrift can't read it back to construct an instance of MyObj.
Although there is a TJSONProtocol which supports to serialize and deserialize, but the generated JSON is not readable, it uses a very simplified JSON format and most of the field names are missing. Not convenient to construct it in tests.
Is there any way to convert thrift objects to readable string and also can convert it back? If TSimpleJSONProtocol supports converting back, which is just what I'm looking for
The main goal of Thrift is to provide efficient serialization and RPC mechanisms. What you want is something that is - at least partially - contrary to that. Human-readable data structures and machine processing efficiency are to a good extent conflicting goals, and Thrift favors the latter over the former.
You already found out about the TSimpleJson and TJson protocols and about their pros and cons, so there is not much to add. The only thing that is left to say is this: the protocol/transport stack of Thrift is simple enough.
This simplicity makes it possible to add another protocol based on your specific needs without much or overly complicated work. One could probably even write an XML protocol (if anyone really wants such bloatware) in short time.
The only caveat, especially vis-à-vis your specific case, is the fact that Thrift needs the field ID to deserialize the data. So you either need to store them in the data, or you need some other mechanism which is able to retrieve that field ID based on the field and structure names.

Is there a good "standard" Java interface for XML and JSON readers/writers?

Basically, I want to have an interface for converting Objects to/from their XML or JSON String representation, something like
public interface IStringifier{
/**
Converts the Object to it's String representation, e.g. XML or JSON
*/
public String toString(Object o);
/**
Converts from the String representation (e.g. XML or JSON) to an Object
*/
public Object fromString(String s, Class<?> clazz);
}
Such an interface would be fairly simple to implement in GSON, XStream etc. but by abstracting it you are abstracted from knowing just what is going on underneath. And you are decoupled from one of the many many XML or JSON libraries, so clients are freer to pick their favorite.
Is there any "standard" Java interface for this? Something in Guava, Apache, etc?
(added) None of the answers were what I really wanted ("yes, in javax.obscure.interfaces there's what you want") but thanks for the replies. I'll accept Tom's answer as the most informative/provocative. And maybe I'll clean up the code I have and try to create a standard. :-)
JAXB (JSR-222) is the Java SE/EE standard for converting objects to/from XML. It can be used standalone and is the standard binding layer for JAX-WS (SOAP) and JAX-RS (RESTful) Web Services. Below is a link to an example of specifying an alternate provider via a jaxb.properties file.
http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
There currently isn't a standard API for JSON binding.
I think you're overthinking this. You don't actually care about turning objects into Strings, you want to be able to serialize objects to different formats without knowing what that format is. But who says that different format is a String? What happens when you want your object to be available as a protocol buffer? That's a binary format, not a character format -- so stringify() won't help there. Ultimately, it's up to you to architect your application to be as independent as possible of those details.
XML and JSON are unrelated, so this is actually two questions:
For JSON, although "unofficial", a popular library is GSON.
For XML, see Blaise's answer
One popular JSON-to-Java binding library is Jackson
One popular XML-to-Java binding library is XStream
If you intend to use this in a web application, maybe you would like to consider Spring 3 MVC's facilities for this. Through annotations it does the conversion automatically and you can tell it whether you want XML or JSON (or various other formats). This might be the common interface you are looking for too.

Designing classes around a StAX parsing

This is a design question rather than a Java-specific question, but I'm designing it for Java.
I've been writing some XML pull parsing classes to handle a custom XML response and as I design them, I can't help but think whether there's something better. Maybe someone even has a design pattern for it.
So, here's what my XML may look like:
<ResponseRoot>
<Header>
<RequestId />
<OtherHeaderMetaData />
</Header>
<Body>
...
<!-- Lots of other elements and nested elements -->
...
</Body>
</ResponseRoot>
So depending on the RequestId (a key of sorts), the Body element is different. Given that this is pull parsing, I'd have a large switch statement and lots of if-else-if blocks.
Would it be more efficient for one class with lots of static methods to handle the whole XML stream, or would it make for a better design to have one class responsible for each RequestId?
I was thinking of mapping RequestId to a class name, and then when I hit Body, I use a factory to retrieve the appropriate subparser. Inside that factory, I could even use a mapping of Class instances and use reflection to instantiate the appropriate parser (since not all parsers are needed all the time). Or... use reflection to grab the appropriate static parsing method instead, so I don't need to instantiate parsers that are really just 1-use classes...
Yea, I'm thinking too deeply, but since this is just a personal project, I just got curious about how people design parsing classes around a StAX parser.
So depending on the RequestId (a key of sorts), the Body element is different.
Can you redesign the XML so that a valid body elemt does not depend on the request-ID, but is determined entirely by the surrounding response element? Then document validity (conformance to the DTD) would correspond to message response validity.
Instead of using a switch statement, consider using the state design pattern. That is, implement your document handler as a finite state machine.
I'd definitely go for a separate processor class per request type. Your factory approach sounds good, but don't bother with the reflection stuff, just create those processor objects instead of using reflection, thirty-something bytes of heap space are a very reasonable price for easily readable code.
One thing that is important though with StAX that in the documentation of every processing method you should describe what state that method is expecting the input to be in (e.g.: before or after having processed the opening <body> tag) and where does it leave the input after processing. You can save yourself hours of frustrating debugging this way.
Instead of putting the responsibility of parsing each custom XML object on the StAX parser, why not have the StAX parser create an intermediate representation of the XML object? Then, you could have a factory which would construct a final representation of the XML object using the RequestID. The code would look similar to:
IntermediateObject io = StAX.parse(XML);
FinalObject = Factory.create(io.getRequestID, io);
The upside of using this approach is that you're separating responsibilities. The StAX parser will only parse the XML, while the factory would be responsible for doing further processing with that information.

Categories