Can I create classes from json data similar to jaxb - java

So my code is a client of an api, the data is returned as xml and Ive been able to create valid xsd file from some examples of that xml and then generate some JAXB classes from the schema so my code can now load and work with the xml data without ever having to work directly with Xml.
But unfortunately in the latest version of the api they have dropped xml support and only return json. Is there a json process I can do analogous to my xml process ?
If its not possible from a schema are there solutions so that if I manually create my json classes, I can them use them to automatically martial in raw json data, so at least I only have to deal with json once.
EDIT:Maybe https://github.com/ko5tik/jsonserializer would be useful
UPDATE:FYI so I looked at jsonschema2pojo but that only creates pojos from a schema, and I didnt actually have a json schema, just the actual json. I had a go at creating a schema from the example json I had but didnt get it working for al but the simplest example.
I then looked at http://wiki.fasterxml.com/JacksonInFiveMinutes , Jackson would have been able to use the pojos created by jsonschema2pojo if Id managed to get it working. So I then tried following the example and created a POJO based on the json data I had and it was quite easy, then I then tried full data binding using this and it worked first time.
So in summary Im going to use Jackson for dealing with json returned by the webservice, I'll have to manually create a POJO for each entity but at least it works.

As to answer, maybe try "jsonschema2pojo".
But similar questions have already been asked before:
How can I parse a JSON schema and create a default json object or generate a java class?
Generate Java class from JSON?
Is there a tool to generate a JSON schema from an XML schema through Java?

If you want to create POJOs from a sample JSON file, I've created a (hacky) ruby script that can help. I've added more details in another answer here: https://stackoverflow.com/a/8585423/1109175
You can find the code on github: https://github.com/wotifgroup/json2pojo

I don't think there is a JSON equivalent to XSD, and that makes what you are asking for really hard to implement. For a start, a generator program cannot reliably deduce the Java types that need to be used for the attributes of a JSON object. (In the XML case, you made those deductions and expressed them in the corresponding XSD.)

No, I don't see a way for doing that... JSON is without a schema definition, so there's no meta-data to generate the classes from.
Edit: I stand corrected, there is a schema definition (draft), it has however expired since the beginning of this year, and I have not encountered any schemas provided.

Related

XML schema to Java pojos to json

I'm generating a Java class hierarchy from a complicated xml schema. The content stored in xml (returned via a REST endpoint) is verbose, plus consumers want only subsets of the xml content returned as json (that they define).
I know there are brute force ways to accomplish this, but does anyone know of a more elegant approach? Maybe some kind of mapping that the consumer could pass to the service that would allow them to dynamically select the content (via xpath in the mapping) and also produce custom json wrapping that content?
The consumers will have an understanding of the schema and content structure, but nothing about Java or its object hierarchy.
I know, a lot here. Any suggestions?
You can give Apache Commons JXPath a try. If you have the Java class hierarchy then I assume you have the objects in memory before sending them as XML. With that you can user JXPath to traverse the java objects as if they were XML in XPath fashion.

How to render special XML/JSON Flavours with Playframework

According to James Wards Play Tutorial it's very easy to get a JSON out of your model. Also with XML this should be quite simple.
But most of the time, I have the requirement to build not just an plain XML or JSON Endpoint, but furthermore to deliver special flavours of those. In my case this is GeoJSON or TopoJSON. But also in XML, it could be a simple RSS or ATOM Feed you have to deliver out of your model. Also building a XML fitting to a very nasty XSD schema is still a case sometimes.
What options do you have in play to perform this, or which one of the following would you recommend?:
In case of GeoJSON/TopoJSON: Activate JSON as a template format, and create JSON Templates
In case of ATOM/RSS: Just use an XML Template
Some way to modify the JSON response coming from toJson(tasks)?
Use of a fancy library which does all that out of the box, and everyone knows about it, except me?
If you're doing GeoJSON, just annotate your objects with Jackson annotations according to the GeoJSON spec, it's not hard. If it is hard, then there are a few libraries out there that come with Java objects with the necessary annotations already for you, eg: https://github.com/opendatalab-de/geojson-jackson
An XML template is probably the simplest from Java.
What's your use case? toJson returns a Jackson JSONNode. You can modify it as much as you want. But the better thing to do would be to use Jackson annotations on your objects to get the format right in the first place.
I think you're referring to Jackson, it can do everything you want. It can even do XML if you want it to.

Play2: Best way to deliver JSON content

Let's say I have REST like endpoints which return JSON data, e.g. from models in my Java Play application. I've found two ways to create the JSON output:
Using JSON templates similar to HTML templates. It could look like this:
{
"name": "${user.name}",
"id": "${user.id}",
. . .
}
What I like about it is the flexibility. I could build a wrapper around the data (for metadata, status messages etc.) with ease. And I easily can influence which things get delivered (things like password fields, timestamps of last login etc. are of course nothing you want to show to the client). A requirement is of course that the content of the template variables should be escaped correctly in order to get valid JSON. What is the best way to do this?
The second approach is to serialize the POJO of the model directly into JSON. Of course this is faster and can be done with less effort. In contrast to the template approach, it is perhaps more reliable since it is an automatic process. BUT: how can I exclude data like password and metadata fields? should I construct a new JSON object with the jackson implementation that only contains the relevant data? Or do I have to create a "json-model" for each model class and transform the real model on each request into the json-model before I can serialize it?
Personally, I like the template approach because of its flexibility. But some of you will say, never construct JSON, XML etc. manually. But is this really a problem in this case, what would you recommend?
Assuming you're using Java, Jackson let you exclude fields using annotations. See: http://jackson.codehaus.org/1.0.0/javadoc/org/codehaus/jackson/annotate/JsonIgnore.html

Convert xml to java

How can I convert xml to java so that it could read the xml document and put it in to a database?
Your question is rather obscure and general. There are a number of options for converting XML to Java objects:
JAXB
XStream
XMLBeans
This article could be useful.
But anyway you will have to read much before getting something more complex to work.
This is all in case you need to map your xml to java objects. If you just need to parse the XML:
dom4j
xerces
JAXP
Check this: http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html
That's how you read xml file. Then you just crate SQL query to insert it into database (JDBC?)
It's not clear at all, but if you are talking about parsing a XML file to do whatever you want with it in Java (also storing it in a database) you have to already ready choices:
using a DOM parser
using a SAX parser
both are covered here just to give you an example, but check documentation for better explaination.
Apparently JAXB can do marshalling/unmarshalling. I've not used it, but it seems to do what you want. From there, you can use an ORM of some type to put your objects in a database, or you can handcraft SQL.
It sounds like you are looking for something like JAXB or Castor. They both let you convert from a Java object -> XML and XML -> Java object.
Check Hyperjaxb3. It is a JAXB plugin which makes schema-derived classes to JPA entities. Thus you can easily do XML <-(JAXB)-> Java <-(JPA)-> RDB.
For this I recommend EclipseLink. EclipseLink offers both JAXB (object-to-XML) and JPA (object-to-Database) support.
The EclipseLink JAXB (MOXy) implementation offers all the extensions you need for mapping JPA entities to XML, for more information see:
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/JPA
Use this https://json2csharp.com/xml-to-java in case you're looking for an online tool, you can then deserialize your object and fill it in the database

Creating multithreaded Java server and clients, but messages have to be in XML format

I've got to write a multithreaded chat program, using a server and clients but each message sent has to be in XML.
Is it simpler/easier just to write out all the code in java, and then try and somehow alter it so the messages are sent in XMl format, or would it be simpler just to try and go for it in XML and hope it works. I'll admit I don't know that much about XML. :)
Also any links to any relevant online help/tutorials would be much appreciated.
Thanks.
When messing with XML in Java, PLEASE consider using JAXB or something similar. It allows you to work with a normal object graph in memory and then serialize that to XML in one operation (and the other way around).
Manipulating XML through the DOM API is a slow way to lose your sanity, do not do it for any non-trivial amount of XML.
I fail to see what the program being multithreaded or a server have to do with it though...
Check out XStream. You can use this to marshall a normal Java object into XML, and back again into an object, without having to do anything instrusive like define interfaces or specify schema etc. i.e. it works out of the box for objects you already have defined. For most cases it's seamless in its default mode.
XStream produces a direct XML serialised representation of a Java object (i.e. XML elements represent each field of a Java object directly). You can customise this further as/when you require. If you want to define persisted objects in terms of schema (XSD) then it's not appropriate. However if you're transporting objects where persistence is short-term and you're not worried about conforming to some schema then it's definitely of use.
e.g.
Person person = new Person("Brian Agnew");
XStream xStream = new XStream();
System.out.println(xStream.toXML(person));
and conversion from XML to the Person object is similarly trivial.
(note XStream is thread-safe)
There is something called XML RPC. This examples pretty much shows what you're looking for:
http://docstore.mik.ua/orelly/xml/jxml/ch11_02.htm
It would be simpler to use existing XMPP clients and servers and not write your own at all.
If this is in fact homework, then I would suggest writing the client and server as you have suggested, using all java, but use a String as the message. You can then easily add parsing of the string to/from XML when all other parts are working.
I would suggest to also have a look at Betwixt and Digester. For Digester there are some tutorials which can be found in the Digister-wiki. Betwixt provides some pretty good tutorials right on its website.
Additionally to these two tools there is a list of alternatives that can be found in the Reference section of http://wiki.apache.org/commons/Digester/WhyUseDigester
You're on the right page trying to break the task into smaller pieces.

Categories