1

I'm using Jackson to serialize and deserialize JSON objects to and from POJO-s.

One of the elements I'm trying to create is a list of arrays (I think that's what this would be called).

"Images": [
{}
],

I've tried:

public ArrayList<String> Images = new ArrayList<String>();

and then just didn't add anything to it then called the object mapper.

That unfortunately gave me just a list:

"Images":[
]

I then tried to make it an list of string arrays:

public ArrayList<String[]> Images = new ArrayList<String[]>();

I added an empty array to my ArrayList:

String[] tempArray = {};
Images.add(tempArray);

But that gave me:

"Images":[
     []
],

How can I get the needed format?

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
Anton
  • 761
  • 17
  • 40

2 Answers2

2

What you describing is a list of objects, which would be:

public ArrayList<yourObject> Images = new ArrayList<yourObject>();

This would give you the:

"Images": [
{}
]

If you want a list of arrays, you would do:

public ArrayList<ArrayList<yourObject> Images = new ArrayList<ArrayList<yourObject>();

this would give you:

    "Images":[
     []
     ]
BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
1

JSON not-primitives in Java can be represented by:

  1. JSON Array - [] => java.util.List or array.
  2. JSON Object - {} => java.util.Map or POJO class.

If you need empty JSON Object you can use empty map or empty POJO - POJO without properties or with all properties set to null and with ObjectMapper set to ignore null-s.

Simple example which generates desired output could look like below:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Collections;
import java.util.List;
import java.util.Map;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        String json = mapper.writeValueAsString(new Root());
        System.out.println(json);
    }

}

class Root {

    private static final List<Map<String, Object>> EMPTY_MAP_IN_ARRAY = Collections.singletonList(Collections.emptyMap());

    @JsonProperty("Images")
    private List<Map<String, Object>> images = EMPTY_MAP_IN_ARRAY;

    public List<Map<String, Object>> getImages() {
        return images;
    }

    public void setImages(List<Map<String, Object>> images) {
        this.images = images;
    }
}

Above code prints:

{"Images":[{}]}
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146