【问题标题】:Jackson : Converting JSON property to nested Object with Dot NotationJackson:使用点表示法将 JSON 属性转换为嵌套对象
【发布时间】:2012-02-13 19:39:22
【问题描述】:

我有一个这样的 JSON

{ "id":1, "name":"Jack", "parent.id":2 }

注意“parent.id”属性上的点

是否可以将这些 JSON 映射到以下类?

class Child {
    private int id;
    private String name;

    private Parent parent;

    //getter and setter methods
}

class Parent {
    private int id;
    private String name;

    //getter and setter methods
}

所以映射结果将类似于以下语句:

Parent parent = new Parent();
parent.setId(2);

Child child = new Child();
child.setId(1);
child.setName("Jack");
child.setParent(parent); // Here is the result

【问题讨论】:

  • 你可以通过定义自己的MessageBodyReader来做到这一点,但我不得不问......为什么?
  • 因为我使用的是 ExtJS,它发送的 JSON 格式如上。
  • 我们的所有解决方案中都有 Ext.js 客户端。让 GUI 开发人员修复他们的模型。

标签: java json spring jackson


【解决方案1】:

你可以转换这个

{ "id":1, "name":"Jack", "parent.id":2 }

进入这个

{ "id":1, "name":"Jack", "parent": { "id":2 } }

通过使用这个

// I'm using jQuery here 
$.fn.serializeObject = function() {
  var arrayData, objectData;
  arrayData = this.serializeArray();
  objectData = {};

  $.each(arrayData, function() {
    var value;

    if (this.value != null) {
      value = this.value;
    } else {
      value = '';
    }

    // search for "parent.id" like attribute
    if (this.name.indexOf('.') != -1) {
      var attrs = this.name.split('.');
      var tx = objectData;

      for (var i = 0; i < attrs.length - 1; i++) {
        if (objectData[attrs[i]] == undefined)
          objectData[attrs[i]] = {};
        tx = objectData[attrs[i]];
      }
      tx[attrs[attrs.length - 1]] = value;
    } else {
      if (objectData[this.name] != null) {
        if (!objectData[this.name].push) {
          objectData[this.name] = [objectData[this.name]];
        }

        objectData[this.name].push(value);
      } else {
        objectData[this.name] = value;
      }
    }
  });

  return objectData;
};

然后您可以使用JSON.serialize() 序列化您的代码。

如果您使用的是 Jackson,那么您可以通过执行以下任何操作来反序列化 JSON 请求字符串:

1.创建一个自定义 Jackson 反序列化模块

2。自己解析 JSON

public Child parseJackson(String jsonRequest) {
  // what we need
  ObjectMapper mapper;
  JsonNode root, parentNode;

  // your models
  Child child;
  Parent parent;

  // assign
  mapper = new ObjectMapper();
  root = mapper.readTree(jsonRequest); // deserialize JSON as tree
  parentNode = root.get("parent"); // get the "parent" branch

  // assign (again)
  child = mapper.readValue(root, Child.class);
  parent = mapper.readValue(parentNode, Parent.class);

  child.setParent(parent);

  return child;
}

这种方法的缺点是你必须解析每个带有嵌套对象的 JsonRequest,当嵌套结构复杂时会很混乱。如果这是一个问题,我建议你做#3

3.创建一个自定义 Jackson ObjectMapper 类来自动化这个过程

这个想法是为 #2 构建通用流程,以便它可以处理任何嵌套请求。

public class CustomObjectMapper extends ObjectMapper {

  // here's the method you need
  @Override
  public <T> T readValue(String src, Class<T> type)
      throws IOException, JsonParseException, JsonMappingException {

    JsonNode root = this.readTree(src);
    try {
      return readNestedValue(root, type);
    } catch (InstantiationException | IllegalAccessException | IOException
        | IllegalArgumentException | InvocationTargetException e) {
      return super.readValue(src, type);
    }

  }

  // if you're using Spring, I suggest you implement this method as well
  // since Spring's MappingJacksonHttpMessageConverter class will call 
  // this method.
  @Override
  public <T> T readValue(InputStream src, JavaType type)
      throws IOException, JsonParseException, JsonMappingException {

    JsonNode root = this.readTree(src);
    try {
      return readNestedValue(root, (Class<T>) type.getRawClass());
    } catch (InstantiationException | IllegalAccessException | IOException
        | IllegalArgumentException | InvocationTargetException e) {
      return super.readValue(src, type);
    }

  }

  // we need this to recursively scan the tree node
  protected <T> T readNestedValue(JsonNode root, Class<T> type)
      throws InstantiationException, IllegalAccessException, IOException,
        IllegalArgumentException, InvocationTargetException {

    // initialize the object use ObjectMapper's readValue
    T obj = super.readValue(root, type);
    Iterator it = root.getFieldNames();
    while (it.hasNext()) {
      String name = (String) it.next();
      String camelCaseName = name.substring(0, 1).toUpperCase() + name.substring(1);
      JsonNode node = root.get(name);

      Field f;
      try {
        f = type.getDeclaredField(name);
      } catch (NoSuchFieldException e) {
        f = findFieldInSuperClass(name, type.getSuperclass());
      }
      // if no field found then ignore
      if (f == null) continue; 

      Method getter, setter;
      try {
        getter = type.getMethod("get" + camelCaseName);
      } catch (NoSuchMethodException e) {
        getter = findGetterInSuperClass("get" + camelCaseName, type.getSuperclass());
      }
      // if no getter found or it has been assigned then ignore
      if (getter == null || getter.invoke(obj) != null) continue;

      try {
        setter = type.getMethod("set" + camelCaseName);
      } catch (NoSuchMethodException ex) {
        setter = findSetterInSuperClass("set" + camelCaseName, type.getSuperclass(), f.getType());
      }
      // if no setter found then ignore
      if (setter == null) continue;

      setter.invoke(obj, readNestedValue(node, f.getType()));
    }

    return obj;
  }

  // we need this to search for field in super class
  // since type.getDeclaredField() will only return fields that in the class
  // but not super class
  protected Field findFieldInSuperClass(String name, Class sClass) {
    if (sClass == null) return null;
    try {
      Field f = sClass.getDeclaredField(name);
      return f;
    } catch (NoSuchFieldException e) {
      return findFieldInSuperClass(name, sClass.getSuperclass());
    }
  }

  protected Method findGetterInSuperClass(String name, Class sClass) {
    if (sClass == null) return null;
    try {
      Method m = sClass.getMethod(name);
      return m;
    } catch (NoSuchMethodException e) {
      return findGetterInSuperClass(name, sClass.getSuperclass());
    }
  }

  protected Method findSetterInSuperClass(String name, Class sClass, Class type) {
    if (sClass == null) return null;
    try {
      Method m = sClass.getMethod(name, type);
      return m;
    } catch (NoSuchMethodException e) {
      return findSetterInSuperClass(name, sClass.getSuperclass(), type);
    }
  }
}

如果您使用的是 Spring,那么最后一步是将此类注册为 Spring bean。

<mvc:annotation-driven>
    <mvc:message-converters>
      <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
         <property name="objectMapper">
            <bean class="x.y.z.CustomObjectMapper"/>
         </property>
      </bean>
    </mvc:message-converters>
  </mvc:annotation-driven>

通过这些设置,您可以轻松使用

@RequestMapping("/saveChild.json")
@ResponseBody
public Child saveChild(@RequestBody Child child) {
  // do something with child
  return child;
}

希望这会有所帮助:)

【讨论】:

    猜你喜欢
    • 2016-10-06
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多