2

I want to convert Java object to JSON string. Lets say the object looks like this:

public class User{
    private Long id;
    private String firstName;
}

And the json should look like this:

{
    "inputFields":[
        {
            "name":"id",
            "value":"123"
        },
        {
            "name":"firstName",
            "value":"George"
        }
    ]
}

Tried to use Jackson, but it looks like it doesn't provide such kind of serialization.

5
  • You Need Custom Serializer to Serialize the array of Class User Object. Commented Apr 1, 2016 at 8:58
  • This is what you need to do: baeldung.com/jackson-custom-serialization Commented Apr 1, 2016 at 8:59
  • 1
    Why do you need such an awkward JSON structure? Wouldn't it be better to have "id":"123","name":"George"? Commented Apr 1, 2016 at 9:00
  • You might want to have a look at this thread - How to serialize Object to JSON? Commented Apr 1, 2016 at 9:05
  • @BadCash, there always is a reason. For this case I am trying to integrate with external WebService, and it requires such structure. Commented Apr 1, 2016 at 9:07

3 Answers 3

2

Jackson can use custom serializer where you can have control in generating the output. The following are the step to do this:

Annotate your POJO to use a custom serializer

@JsonSerialize(using = CustomSerializer.class)
static class User{
    public Long id;
    public String firstName;

    public User(Long id, String firstName) {
        this.id = id;
        this.firstName = firstName;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
}

Declare the serialzer

static class CustomSerializer extends JsonSerializer{

    @Override
    public void serialize(Object value, JsonGenerator jgen, SerializerProvider serializers) throws IOException, JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeArrayFieldStart("inputFields");

        Field[] fields = value.getClass().getDeclaredFields();

        for (Field field : fields) {
            try {
                field.setAccessible(true);
                jgen.writeStartObject();
                jgen.writeObjectField("name", field.getName());
                jgen.writeObjectField("value", field.get(value));
                jgen.writeEndObject();
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }

        }

        jgen.writeEndArray();
        jgen.writeEndObject();
    }
}

A simple test

public static void main(String[] args) throws JsonProcessingException {
    User user = new User(1L, "Mike");
    ObjectMapper om = new ObjectMapper();
    om.writeValueAsString(user);
    System.out.println(om.writeValueAsString(user));
}

And the output will be

{"inputFields":[{"name":"id","value":1},{"name":"firstName","value":"Mike"}]}
Sign up to request clarification or add additional context in comments.

4 Comments

what version of jackson are you using ?
in the example i used jackson 2.6.1
add field.setAccessible(true); to the loop and I will accept this answer as the most "on point" and elegant.
true, to prevent accessibility using reflection one should set that flag. thanks
0

Create an InputFields class and move the User object data to it before converting to json.

Edit: The InputFields class would obviously have the same structure as the desired json result.

3 Comments

And make the field a Collection inside the InputFields class. Or create a custom converter.
@stepanian actually, the inputFields is not a big problem, the problem is structure of name-value pairs
I understand that. The InputFields class will have that structure.
0

Just a example of stepanian's answer, but i prefer dumitru's way to implement a CustomSerializer.

  1. create a InputField class

    public class InputField {
    
        private String name;
        private String value;
    
        public String getValue() {
            return value;
        }
    
        public void setValue(String value) {
            this.value = value;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
    }
    
  2. parse User

    public static List<InputField> parseInputFields(Object model) {
        List<InputField> inputFields = new ArrayList<InputField>();
    
        Field[] field = model.getClass().getDeclaredFields();
        try {
            for (int j = 0; j < field.length; j++) {
    
                InputField inputField = new InputField();
    
                inputField.setName(field[j].getName());
                inputField.setValue(String.valueOf(field[j].get(model));
    
                inputFields.add(inputField);
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    
        return inputFields;
    } 
    
  3. test

    public static void main(String[] args) throws JsonProcessingException {
        User user = new User(1L, "Mike");
    
        Map<String, Object> tmpMap=new HashedMap();
        tmpMap.put("inputFields", parseInputFields(user));
    
        ObjectMapper om = new ObjectMapper();
        System.out.println(om.writeValueAsString(tmpMap));
    }
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.