Gnana
Gnana

Reputation: 614

Need to converting POJO to JSON using net.sf.json JsonSerializer with maintaining the POJO attribute ordering

I'm using net.sf.json API for all JSON operations. I'm trying to convert a POJO to JSON using JSONSerializer.toJSON(POJO, JsonConfig). I would like the resulting JSON to have the POJO attributes in the same order as specified in the POJO. But what I'm seeing is the serialization results in alphabetical order of the POJO properties.

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"}

I actually want {"name":"John","age":50}

I tried this hack,

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}`

Is there any better way?

I do not want to move to Jackson which has better capabilities since net.sf.json is used in the entire project.

Upvotes: 0

Views: 1536

Answers (1)

Gnana
Gnana

Reputation: 614

I tried this approach and I guess this seems to be better

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}

Upvotes: 1

Related Questions