5

Suppose I have a data model like:

public class MyModel {
    private String someString;
    private String someJson; // Data structure owned by client, persisted as a CLOB
}

I'm serving the model via a REST API (Jersey) to a client. I know that I could marshal/unmarshal that to something like:

{
    "someStrong": "foo",
    "someJson": "{ someClientThing: \"bar\", someOtherClientThing: \"baz\"}"
}

But I'm looking for something cleaner. Is there a way that I can marshal/unmarshal that to JSON like this?

{
    someStrong: "foo",
    someJson: {
        someClientThing: "bar",
        someOtherClientThing: "baz"
    }
}

I don't want the server to have to know about the data model for someJson, as it's owned by the client. I just want the server to handle persistence of it - so the server would pass it back and forth between the client and database.

Note: It doesn't need to map directly to a string - as long as it can map to something unstructured (not statically defined on the server) that can be stringified before persistence (and unstringified back to that unstructured object on retrieval).

Eric
  • 5,842
  • 7
  • 42
  • 71
  • 2
    Could you work with base64? You can store it directly in BBDD and the client only has to encode before sending request and decode before parsing response which is trivial in most programming languages. Your server variable would be `byte[] someJson` and JAXB would do the encoding/decoding – pedrofb Jul 01 '16 at 11:57

2 Answers2

2

It's possible if json doesn't have arrays, as in your example:

{ "someClientThing": "bar", "someOtherClientThing": "baz"}

For such simple case the solution is implementation of bidirectional conversion json-string<->org.w3c.dom.Document instance in own DomHandler. Attach the handler to the field:

@XmlRootElement
@XmlAccessorType(FIELD)
    public class MyModel {
    private String someString;
    @XmlAnyElement(value = SomeJsonHandler.class)
    private String someJson; // Data structure owned by client, persisted as a CLOB
}

Enjoy.

Unfortunately there's a big throuble with arrays, because XML Dom doesn't support theirs. After reconversion below json

{ "someClientThing": "bar", "someOtherClientThing": ["baz1","baz2"]}

you will get something like this

{
   "someClientThing": "bar",
   "someOtherClientThing": {value="baz1"},
   "someOtherClientThing": {value="baz2"}
}
edwgiz
  • 747
  • 5
  • 15
1

Try like this,maybe can help you

public class MyModel {
    private String someString;
    private Map<String, Object> someJson;
}
Martin Dai
  • 47
  • 1
  • 10
  • Hm, that wouldn't work for more complex structures, would it? I should have made my example more complex, but it should be an arbitrarily complex structure - objects with objects with arrays of objects with arrays, etc – Eric Jul 05 '16 at 14:31