नियंत्रक में मैं जेसन सरणी बना देता हूं। अगर मैं List<JSONObject>
लौट यह ठीक है:वसंत: वापसी @ResponseBody "ResponseEntity <सूची <JSONObject>>"
@RequestMapping(value="", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody List<JSONObject> getAll() {
List<Entity> entityList = entityManager.findAll();
List<JSONObject> entities = new ArrayList<JSONObject>();
for (Entity n : entityList) {
JSONObject entity = new JSONObject();
entity.put("id", n.getId());
entity.put("address", n.getAddress());
entities.add(entity);
}
return entities;
}
लेकिन मैं JSON सारणी और HTTP स्थिति कोड की जरूरत है:
Multiple markers at this line
- The constructor ResponseEntity<JSONObject>(List<JSONObject>, HttpStatus) is undefined
- Type mismatch: cannot convert from ResponseEntity<JSONObject> to
ResponseEntity<List<JSONObject>>
- Type mismatch: cannot convert from ResponseEntity<JSONObject> to JSONObject
कैसे कर सकते हैं:
@RequestMapping(value="", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<List<JSONObject>> getAll() {
List<Entity> entityList = entityManager.findAll();
List<JSONObject> entities = new ArrayList<JSONObject>();
for (Entity n : entityList) {
JSONObject Entity = new JSONObject();
entity.put("id", n.getId());
entity.put("address", n.getAddress());
entities.add(entity);
}
return new ResponseEntity<JSONObject>(entities, HttpStatus.OK); // XXX
}
ग्रहण XXX लाइन में त्रुटि देख मैं जेसन + http जवाब वापस?
@RequestMapping(value="/{address}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<JSONObject> getEntity(@PathVariable("address") int address) {
Entity n = entityManager.findByAddress(address);
JSONObject o = new JSONObject();
o.put("id", n.getId());
o.put("address", n.getAddress());
return new ResponseEntity<JSONObject>(o, HttpStatus.OK);
}
मुझे लगता है कि यह सिर्फ किया गया 'लौट नई ResponseEntity <सूची> (संस्थाओं है चाहिए, HttpStatus। ठीक है); सही? भले ही, नीचे आपका समाधान ठीक है। –
adchilds
धन्यवाद, यह काम करता है। क्या बेहतर है? 'ResponseEntity <सूची>' या 'ResponseEntity
पठनीयता की चिंताओं के लिए, पूर्व मेरी राय में बेहतर है। – adchilds