How to send a Map in JSON

Viewed 57234

I have an object that I need to upload in JSON

public class Contribution<T extends MovieRequest> {
    private Set<T> elementsToAdd;
    private Map<Long, T> elementsToUpdate;
    private Set<Long> idsToDelete;
}

I want to send this object in JSON using swagger

{
  "elementsToAdd": [
    {
      "country": "USA",
      "title": "string"
    }
  ],
  "elementsToUpdate": {},
  "numbersToDelete": [
    0
  ]
}

I do not know how to put an object in "elementsToUpdate": {},. As a key I want to put Long, and int he value put object.

key (Long), value (object)

I tried this way

    "elementsToUpdate": {
   {
      1 : {
      "country": "USA",
      "title": "string"
      }
   }
  }

but throws the error

JSON parse error: Unexpected character ('{' (code 123)): was expecting double-quote to start field name
2 Answers
  1. Key always should be string.
  2. Why it still doesn't work? Because the error is caused by the redundant brace inside of "elementsToUpdate". Below is an example:
"elementsToUpdate": {
  {  // redundant
    "1": {
      "country": "USA",
      "title": "string"
    }
  }  // redundant
}

correct one : 
"elementsToUpdate": {
    "1": {
      "country": "USA",
      "title": "string"
    }
}

Below is the complete example where I have converted a class to JSON string and back. You can use the same as reference. The point here is I have used TypeReference class to tell JSON that I have a class Contribution of type MovieRequest. Your code inside the project which reads the JSON has to be like this.

The Main Test Class

public class Test1
{
    public static void main(String[] args) throws IOException{
        //Creating object of the contribution class.
       Contribution<MovieRequest> c = new Contribution<>();

        Set<MovieRequest> set = new HashSet<>();
        set.add(getMovieObject());
        set.add(getMovieObject());
        set.add(getMovieObject());

        Map<Long, MovieRequest> map = new HashMap<>();
        map.put(1L, getMovieObject());
        map.put(2L, getMovieObject());
        map.put(3L, getMovieObject());

        Set<Long> set2 = new HashSet<>();
        set2.add(1L);
        set2.add(2L);
        set2.add(3L);

        c.setElementsToAdd(set);
        c.setElementsToUpdate(map);
        c.setIdsToDelete(set2);

        //Using Jackson for Conversion.
        ObjectMapper mapper = new ObjectMapper();
        String value = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(c);
        //JSON String
        System.out.println(value);

        //Converting JSON string back to Object
        //here I am using TyperReference to tell JSON that this is the type of the class
        Contribution<MovieRequest> c1 =  mapper.readValue(value,  new TypeReference<Contribution<MovieRequest>>() { });
        System.out.println(c1);
    }

    //Just some class to spit out random strings. You can ignore it in ur example. Just add some random strings and return objects.
    private static MovieRequest getMovieObject()
    {
        MovieRequest m1 = new MovieRequest();
        m1.setCountry(randomString());
        m1.setTitle(randomString());
        return m1;
    }


    //This is a random string generator. Ignore this.
    public static String randomString()
    {
        return RandomStringUtils.randomAlphanumeric(17);
    }
}

The Bean classes

class Contribution<T extends MovieRequest>
{
    private Set<T> elementsToAdd;

    private Map<Long, T> elementsToUpdate;

    private Set<Long> idsToDelete;

    /**
     * @return the elementsToAdd
     */
    public Set<T> getElementsToAdd()
    {
        return elementsToAdd;
    }

    /**
     * @param elementsToAdd
     *            the elementsToAdd to set
     */
    public void setElementsToAdd(Set<T> elementsToAdd)
    {
        this.elementsToAdd = elementsToAdd;
    }

    /**
     * @return the elementsToUpdate
     */
    public Map<Long, T> getElementsToUpdate()
    {
        return elementsToUpdate;
    }

    /**
     * @param elementsToUpdate
     *            the elementsToUpdate to set
     */
    public void setElementsToUpdate(Map<Long, T> elementsToUpdate)
    {
        this.elementsToUpdate = elementsToUpdate;
    }

    /**
     * @return the idsToDelete
     */
    public Set<Long> getIdsToDelete()
    {
        return idsToDelete;
    }

    /**
     * @param idsToDelete
     *            the idsToDelete to set
     */
    public void setIdsToDelete(Set<Long> idsToDelete)
    {
        this.idsToDelete = idsToDelete;
    }

    /**
     * @inheritDoc
     */
    @JsonIgnore
    @Override
    public String toString()
    {
        return "Contribution [elementsToAdd=" + elementsToAdd + ", elementsToUpdate="
                + elementsToUpdate + ", idsToDelete=" + idsToDelete + "]";
    }

}

class MovieRequest
{
    private String country;

    private String title;

    /**
     * @return the country
     */
    public String getCountry()
    {
        return country;
    }

    /**
     * @param country
     *            the country to set
     */
    public void setCountry(String country)
    {
        this.country = country;
    }

    /**
     * @return the title
     */
    public String getTitle()
    {
        return title;
    }

    /**
     * @param title
     *            the title to set
     */
    public void setTitle(String title)
    {
        this.title = title;
    }

    /**
     * @inheritDoc
     */
    @JsonIgnore
    @Override
    public String toString()
    {
        return "MovieRequest [country=" + country + ", title=" + title + "]";
    }

}

Output

{
  "elementsToAdd" : [ {
    "country" : "08Pv3v048kXbz9gRg",
    "title" : "ljuih0hctsTRC2FfY"
  }, {
    "country" : "847JRWP65Fum3Ttm5",
    "title" : "Z7kS3YGbyjKOVTX6p"
  }, {
    "country" : "JmkjGDW81BMDyyPgj",
    "title" : "X3c5J0xurKsbXNgCY"
  } ],
  "elementsToUpdate" : {
    "1" : {
      "country" : "ItZF8GgzFMAs8WRk5",
      "title" : "tMnb1z1ooSUOuqEMS"
    },
    "2" : {
      "country" : "HOhk142Q6brYmOMWC",
      "title" : "7FQv9TVj6nOjxU2Ri"
    },
    "3" : {
      "country" : "hJYbY33KOsMbJN2o6",
      "title" : "uW5zEkoosux9QsC44"
    }
  },
  "idsToDelete" : [ 1, 2, 3 ]
}
Contribution [elementsToAdd=[MovieRequest [country=08Pv3v048kXbz9gRg, title=ljuih0hctsTRC2FfY], MovieRequest [country=847JRWP65Fum3Ttm5, title=Z7kS3YGbyjKOVTX6p], MovieRequest [country=JmkjGDW81BMDyyPgj, title=X3c5J0xurKsbXNgCY]], elementsToUpdate={1=MovieRequest [country=ItZF8GgzFMAs8WRk5, title=tMnb1z1ooSUOuqEMS], 2=MovieRequest [country=HOhk142Q6brYmOMWC, title=7FQv9TVj6nOjxU2Ri], 3=MovieRequest [country=hJYbY33KOsMbJN2o6, title=uW5zEkoosux9QsC44]}, idsToDelete=[1, 2, 3]]
Related