Pregunta

my javascript looks like this:

{
   a: "This is a Test",
   b: {
         test1: "bla",
         test2: "blub
      }
}

Now I send this object as stringifies Json Object to my Java Backend (Jax-RS) and want to parse it back into Java Objects. I am using Jackson for this. Problem is, I don't know how to map an object with different types in it. (String/Map) Can anyone help?

¿Fue útil?

Solución

With the json like this: { "a": "This is a Test"," "b": { "test1": "bla", "test2": "blub" } }

You can try this following code:

public static void main(String[] args) 
        throws JsonParseException, JsonMappingException,IOException {
    String json = "{\"a\": \"This is a Test\",\"b\": {\"test1\": \"bla\",\"test2\": \"blub\"}}";
    System.out.println(json);
    JObj obj = new ObjectMapper().readValue(json, JObj.class);
    System.out.println(obj);
}

static class JObj {
    String              a;
    Map<String, String> b;
    public String getA() {return a;}
    public void setA(String a) {this.a = a;}
    public Map<String, String> getB() {return b;}
    public void setB(Map<String, String> b) {this.b = b;}
    @Override
    public String toString() {return "JObj [a=" + a + ", b=" + b + "]";}
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top