【问题标题】:How to send a Map in JSON如何以 JSON 格式发送地图
【发布时间】:2017-11-26 17:11:29
【问题描述】:

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

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

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

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

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

键(长),值(对象)

我试过这种方式

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

但会抛出错误

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

【问题讨论】:

  • 键需要是 JSON 的字符串:"1": { ... } JSON 错误消息非常清楚 “期待双引号以开始字段名称”
  • 另外,JSON 对象不能包含没有键的 JSON 对象。
  • 但它也不起作用。 pastebin.com/0uwYDbpB

标签: java json swagger


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

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

【讨论】:

    【解决方案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);
        }
    }
    

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

    输出

    {
      "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]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-24
      • 2012-04-02
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      • 2015-04-11
      • 2013-08-05
      • 2016-10-17
      相关资源
      最近更新 更多