如何在 JSON 中发送地图

4 java json swagger

我有一个需要以 JSON 格式上传的对象

public class Contribution<T extends MovieRequest> {
    private Set<T> elementsToAdd;
    private Map<Long, T> elementsToUpdate;
    private Set<Long> idsToDelete;
}
Run Code Online (Sandbox Code Playgroud)

我想使用 swagger 以 JSON 格式发送此对象

{
  "elementsToAdd": [
    {
      "country": "USA",
      "title": "string"
    }
  ],
  "elementsToUpdate": {},
  "numbersToDelete": [
    0
  ]
}
Run Code Online (Sandbox Code Playgroud)

我不知道如何将对象放入"elementsToUpdate": {},. 作为一个键,我想把 Long 和 int 值放在 put 对象上。

键(长),值(对象)

我试过这种方式

    "elementsToUpdate": {
   {
      1 : {
      "country": "USA",
      "title": "string"
      }
   }
  }
Run Code Online (Sandbox Code Playgroud)

但抛出错误

JSON parse error: Unexpected character ('{' (code 123)): was expecting double-quote to start field name
Run Code Online (Sandbox Code Playgroud)

saf*_*ron 5

  1. 键始终应该是字符串。
  2. 为什么它仍然不起作用?因为错误是由“elementsToUpdate”内部的多余大括号引起的。下面是一个例子:
"elementsToUpdate": {
  {  // redundant
    "1": {
      "country": "USA",
      "title": "string"
    }
  }  // redundant
}

correct one : 
"elementsToUpdate": {
    "1": {
      "country": "USA",
      "title": "string"
    }
}
Run Code Online (Sandbox Code Playgroud)


utk*_*h31 2

下面是完整的示例,其中我将类转换为 JSON 字符串并返回。您可以使用相同的作为参考。这里的重点是我曾经TypeReference class告诉 JSON 我有一个类型Contribution为 的类MovieRequest。项目中读取 JSON 的代码必须如下所示。

主要测试类

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Bean 类

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 + "]";
    }

}
Run Code Online (Sandbox Code Playgroud)

输出

{
  "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]]
Run Code Online (Sandbox Code Playgroud)