如何在spring rest api中将字符串转换为json格式

新手上路,请多包涵

这是代码:

 @RequestMapping(value="/find/city={city}", method=RequestMethod.GET)
public @ResponseBody String getCity(@PathVariable String city) throws JsonParseException, IOException
{
  ObjectMapper mapper = new ObjectMapper();
  SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAllExcept("id","miscellaneous","country","foundin","code","latlong","state");
  FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter);
  String content = "";
  StringBuilder builder = new StringBuilder();
  List<Master_City> list = City_Repository.findByCityLikeIgnoreCase(city);
 for (Master_City json : list)
  {
     builder.append( mapper.writer(filters).writeValueAsString(json));
    }
 content = builder.toString();
 return content;
}

输出不在 json 中,它是一个字符串:

 {"indexid":65,"city":"Barcelona"}{"indexid":158,"city":"Dillons Bay"}     {"indexid":232,"city":"East London"}{"indexid":411,"city":"Londonderry"{"indexid":587,"city":"Thessaloniki"}{"indexid":818,"city":"Bouillon"}{"indexid":1719,"city":"Flin Flon"}{"indexid":2073,"city":"Clonmel"}

我需要这种格式:

[ { “indexid”: “425”, “city”: “Flin Flon” }, { “indexid”: “220”, “city”: “伦敦” }, { “indexid”: “525”, “city” : “朗年” } ]

原文由 Naresh Gounder 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 448
1 个回答

您可以使用 Spring Boot JSONObject

例子 :

 String content = "{"id":1,"name":"ram"}";
JSONObject jsonObject= new JSONObject(content );

之后,您可以从 spring 控制器返回 jsonObject。

这里 依赖检查最新版本:

 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-configuration-processor</artifactId>
 <version>2.0.1.RELEASE</version>
</dependency>

原文由 Bheem Singh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题