Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to map a JSON object to a string with Moxy?

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

like image 652
Eric Avatar asked Oct 31 '22 01:10

Eric


2 Answers

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"}
}
like image 182
edwgiz Avatar answered Nov 15 '22 05:11

edwgiz


Try like this,maybe can help you

public class MyModel {
    private String someString;
    private Map<String, Object> someJson;
}
like image 38
Martin Dai Avatar answered Nov 15 '22 05:11

Martin Dai