0

我将 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。

4

1 回答 1

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}
于 2014-08-27T21:19:51.620 回答