【问题标题】:Need to converting POJO to JSON using net.sf.json JsonSerializer with maintaining the POJO attribute ordering需要使用 net.sf.json JsonSerializer 将 POJO 转换为 JSON,并维护 POJO 属性排序
【发布时间】:2014-10-21 12:49:44
【问题描述】:

我将 net.sf.json API 用于所有 JSON 操作。我正在尝试使用 JSONSerializer.toJSON(POJO, JsonConfig) 将 POJO 转换为 JSON。 我希望生成的 JSON 具有与 POJO 中指定的顺序相同的 POJO 属性。但我看到的是 序列化结果按 POJO 属性的字母顺序排列。

public class Person {

    private String name;
    private int age;

    // getters and setters`enter code here`
}

Person p = new Person();
p.setName("John");
p.setAge(50);

JSONSerializer.toJSON(p) // {"age":50,"name":"John"}

我实际上想要 {"name":"John","age":50}

我试过这个技巧,

public class Person {

    private String _1_name;
    private int _2_age;

    // getters and setters
}

JsonConfig config = new JsonConfig();

config.registerJsonPropertyNameProcessor(Person.class, new PropertyNameProcessor() {

        @Override
        public String processPropertyName(Class arg0, String arg1) {
            if (arg1.equals("_2_age"))
                return "age";
            if (arg1.equals("_1_name"))
                return "name";          
            return arg1;
        }
    });

JSONSerializer.toJSON(p, config); // {"name":"John","age":50}`

有没有更好的办法?

我不想搬到功能更好的杰克逊,因为整个项目都使用了net.sf.json。

【问题讨论】:

    标签: json pojo json-lib


    【解决方案1】:

    我尝试了这种方法,我想这似乎更好

    Map json = (JSONObject) JSONSerializer.toJSON(p);
    System.out.println(json); // {"age":50,"name":"John"}
    Map newJson = new LinkedHashMap();
    
    // creating a new linkedhashmap with the desired order
    if (json.containsKey("name")) {
        newJson.put("name", json.get("name"));
    }
    
    if (json.containsKey("age")) {
        newJson.put("age", json.get("age"));
    }
    
    System.out.println(JSONObject.fromObject(newJson)); // {"name":"George","age":50}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-06
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多