Question

Context

Currently I'm struggling with correctly modeling a small instruction set I want to send as JSON to an Android application to generate a list of UI parts. Right now it's layered as pretty much a single cascading tree of objects/conditions and meta-data.

Small example:

{ 
"instruction": {
"remarks": "",
"steps": [
  {
    "id": "1234",
    "type": "text",
    "text": "Welcome!"
  },
  {
    "..": "..",
    "type": "image",
    "url": "example.org/image.png"
  },
  ..
 ]
}

But now my instruction set is growing with parts that can sometimes be ignored, not present and parts that need to be filled in. I also want to make the JSON easy to parse, so I think I probably need to make some sort of simple java classes out of it for a parsing library like GSON.

Questions

How should I model this?

  • Should I stick to making a single large JSON document with embedded objects that then translate to separate simple java classes (maybe DTO) files?
  • Or do I need to rethink my instruction set and make it in to several JSON documents (like objects) that include document references?

I'm also a bit confused on how I then would translate those references (if I used them) in to a JSON field that can be read by a library like GSON back in to java code.

The referencing and embedding documents concepts I mentioned are from MongoDB Data Model Design. Since I figured it would probably be easy to save my JSON in a NoSQL database like MongoDB.

Is there maybe another technique I'd be better off using to describe my JSON data at this point such as JSON Schema's?

Was it helpful?

Solution

When object serialization is involved a Data Transfer Object (as you mentioned) gives you the flexibility you need to mirror the JSON structure in an object oriented language. Each tech stack has a way to parse JSON into specific data formats (int's, strings, floats, structs, complex objects, arrays, etc).

Once you have the DTO you are free to map this to other types of classes depending on your needs, be they domain models, view models or some other "model" you need in some obscure corner of your application.

The JSON parsing libraries you can find often use class reflection to infer data types, or provide a way to specify the mapping using config files or a fluent API.

OTHER TIPS

I think your question may have been answered over at Stack Overflow. It involves using the http://json-schema.org/ spec for designing your JSON and converting it with https://github.com/joelittlejohn/jsonschema2pojo. Not sure if the github repo needs any updates for the current version of Java, but it might give you a good starting point.

Licensed under: CC-BY-SA with attribution
scroll top