繁体   English   中英

使用jackson映射JSON对象

[英]Mapping a JSON Object with jackson

我的JavaScript看起来像这样:

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

现在,我将该字符串作为Json对象的字符串发送到我的Java后端(Jax-RS),并想将其解析回Java对象。 我为此使用杰克逊。 问题是,我不知道如何映射其中具有不同类型的对象。 (字符串/映射)任何人都可以帮忙吗?

使用这样的json: { "a": "This is a Test"," "b": { "test1": "bla", "test2": "blub" } }

您可以尝试以下代码:

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 + "]";}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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