如何将一个 JSONObject 列表作为 REST API 响应返回

huangapple go评论74阅读模式
英文:

How to return a list of JSONObject as REST API response

问题

@PostMapping(path = "/searchusersdata")
public ResponseEntity<String> searchUsersData(@RequestBody Map<String, String> searchData) {

    List<JSONObject> finalDataCollection = new ArrayList<>();

    // Making some REST API CALL TO GET 'response' using 'searchData'
    
    String someResponse = response.getBody();
    
    JSONObject object = null;
    
    try {
        object = new JSONObject(someResponse);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    
    String my_data = object.get("my_data").toString();
    
    JSONArray intermediateJA = null;
    
    intermediateJA = new JSONArray(my_data);
    
    for (int i = 0; i < intermediateJA.length(); i++) {
        
        JSONObject item = intermediateJA.getJSONObject(i);
        
        if (item.keySet().contains("user_data")) {
            Object value = item.get("user_data");
            finalDataCollection.add(new JSONObject(value));
        }
        
    }
    
    JSONArray finalJsonArray = new JSONArray(finalDataCollection);

    // Return the final JSON array as a string
    return new ResponseEntity<>(finalJsonArray.toString(), HttpStatus.OK);
}

Please note that in the code above, I've added the necessary parts to convert the finalDataCollection list into a JSON array and then return it as a string using ResponseEntity. This should meet your requirement to return a collection of data in the specified format.

英文:

I am creating a REST API using Spring Boot and using org.json for parsing data retrieved from another different service. From this service I am getting JSON data like in following format

   {

&quot;my_data&quot;:[
{
&quot;user_data&quot;:{
&quot;first_name&quot;:&quot;FirstTest1&quot;,
			&quot;last_name&quot;:&quot;LastTest1&quot;,
			&quot;age&quot;:&quot;25&quot;
}
},
{
&quot;user_data&quot;:{
			&quot;first_name&quot;:&quot;FirstTest2&quot;,
			&quot;last_name&quot;:&quot;LastTest2&quot;,
			&quot;age&quot;:&quot;35&quot;
			}
},{
&quot;user_data&quot;:{
			&quot;first_name&quot;:&quot;FirstTest3&quot;,
			&quot;last_name&quot;:&quot;LastTest3&quot;,
			&quot;age&quot;:&quot;45&quot;
			}
}
],
&quot;count&quot;:10,
&quot;is_safe&quot;:false
}

and I have to transform received data to the following JSON

[
{
&quot;user_data&quot;:{
&quot;first_name&quot;:&quot;FirstTest1&quot;,
			&quot;last_name&quot;:&quot;LastTest1&quot;,
			&quot;age&quot;:&quot;25&quot;
}
},
{
&quot;user_data&quot;:{
			&quot;first_name&quot;:&quot;FirstTest2&quot;,
			&quot;last_name&quot;:&quot;LastTest2&quot;,
			&quot;age&quot;:&quot;35&quot;
			}
},{
&quot;user_data&quot;:{
			&quot;first_name&quot;:&quot;FirstTest3&quot;,
			&quot;last_name&quot;:&quot;LastTest3&quot;,
			&quot;age&quot;:&quot;45&quot;
			}
}
]

I know I can use a POJO to map the data and send it (already doing this) but here the issue is that the data received from another service is not fixed e.g. it may or may mot have "first_name" or may have a different field like "country". So, in this situation I can not make POJO beforehand.

After going through some online resources I made some changes and my POST Controller method looks like this.

@PostMapping(path = &quot;/searchusersdata&quot;)
public RETURN_SOMETHING  searchUsersData(@RequestBody Map&lt;String, String&gt; searchData) {

List&lt;JSONObject&gt;  finalDataCollection = new ArrayList&lt;JSONObject&gt;();

//Making some REST API CALL TO GET &#39;response&#39; using &#39;searchData&#39;

String someResponse = response.getBody();

			JSONObject object = null;
			
			try {
				 object = new JSONObject(someResponse);
			} catch (JSONException  e) {
				e.printStackTrace();
			}
			
			String my_data= object.get(&quot;my_data&quot;).toString();			
			
			JSONArray  intermediateJA = null;
			
			intermediateJA = new JSONArray (my_data);
			
			for(int i = 0; i &lt; intermediateJA.length(); i++) {
				
				JSONObject item = intermediateJA.getJSONObject(i);
				
				if (item.keySet().contains(&quot;user_data&quot;))
		        {
		            Object value = item.get(&quot;user_data&quot;);
		            finalDataCollection.add(new JSONObject(value));
		        }
				
			}
			
			
			//WHAT TO RESTURN HERE
			}

Now, I don't know what to return hare. For a single JSONObject we can use return new ResponseEntity&lt;&gt;(return_data.toMap(), HttpStatus.OK); but for a collection I don't know. I am open to suggestion if I have to do it in entirely different way. I also know that with gson or jackson it might be easier but I have to use org.json.

答案1

得分: 1

用 JsonArray 替代 List,并使用 ResponseEntity 进行返回。

示例:

JsonArray jsonArray = new JsonArray();
JsonObject jsonObject = new JsonObject();
jsonArray.add(jsonObject);
return new ResponseEntity(jsonArray.toString(), HttpStatus.OK);
英文:

instead of List<JSONObject> , use JsonArray and use ResponseEntity to return it.

Example

        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonArray.put(jsonObject);
        return new ResponseEntity( jsonArray.toString(), HttpStatus.OK);

huangapple
  • 本文由 发表于 2020年9月1日 04:48:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63677993.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定