Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert from string into json format in spring rest api

this is the code:

@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;
}

output is not in json ,it's a string:

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

I need in this format:

[ { "indexid": "425", "city": "Flin Flon" }, { "indexid": "220", "city": "London" }, { "indexid": "525", "city": "Longyear" } ]

like image 311
Naresh Gounder Avatar asked Dec 18 '22 15:12

Naresh Gounder


1 Answers

You can use Spring boot JSONObject

Example :

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

After that you can return jsonObject from your spring controller.

dependency check the latest version from here:

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-configuration-processor</artifactId>
 <version>2.0.1.RELEASE</version>
</dependency>
like image 136
Bheem Singh Avatar answered Jan 03 '23 16:01

Bheem Singh