這是代碼:如何從字符串轉換成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」, 「城市」: 「長年」 } ]
也許你想給我們你的想法JSON是解釋響應。對我而言,這是一種基於字符串的格式化數據的方式。就像你發佈爲「輸出」的東西一樣。 – GhostCat