2016-07-14 62 views
-4

这是代码:如何从字符串转换成JSON格式春季REST API

@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”, “城市”: “弗林弗伦” },{ “IndexID为”: “220”, “城市”: “伦敦” }, { “IndexID为”: “525”, “城市”: “长年” } ]

+0

也许你想给我们你的想法JSON是解释响应。对我而言,这是一种基于字符串的格式化数据的方式。就像你发布为“输出”的东西一样。 – GhostCat

回答

1

我需要以json格式。

简答:JSON格式IS STRING。


龙酮(从wikipedia说明)

(JSON)是使用人类可读的文本传输由属性 - 值对的数据对象的开放式标准格式。它是用于异步浏览器/服务器通信的最常用的数据格式.....

正如你所看到的,你得到的字符串,具有正确的attribte - 值对格式,所以你可以给它回 [{“IndexID为”:“425”,“城市”:到Java对象,或者您可以在需要


我需要这种格式在纯文本文件存储获得原始的Java对象“ Flin Flon“},{”indexid“:”220“,”city“:”London“},{”indexid“:”525“,”city“:”Longyear“}]

如果你需要的是引用数字,只需将其类型改为String即可,因为id是数字格式,所以不需要引号。

0

你想要做的是一个json数组,并且你可以使用 Gson库来将对象转换为json。

试试这个:

Gson gson = new Gson();  
content = gson.toJson(list); //your list of Master_City 

你的结果:

[{ “IndexID为”:65, “城市”: “巴塞罗那”},{ “IndexID为”:158, “城市”:” Dillons Bay“},{”indexid“:232,”city“:”East London“},{”indexid“:411,”city“:”Londonderry“},{”indexid“:587,”city“塞萨洛尼基“},{”indexid“:818,”city“:”Bouillon“},{”indexid“:1719,”city“:”Flin Flon“},{”indexid“:2073,”city“ “}]

依赖关系:

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> 
<dependency> 
    <groupId>com.google.code.gson</groupId> 
    <artifactId>gson</artifactId> 
    <version>2.7</version> 
</dependency> 
0

在HTTP请求中必须设置与内容类型=“应用/ JSON的”头然后它会给以JSON格式