简体   繁体   中英

Can I create classes from json data similar to jaxb

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.

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

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.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM