[英]Java Json Object to Json Array Conversion
Im new to java.I am trying to get data from stored procedure and convert it into json array.我是 java 的新手。我正在尝试从存储过程中获取数据并将其转换为 json 数组。 But Im facing some problems with my code.
但是我的代码面临一些问题。
/*** Get data from stored procedure ***/
Map<String, Object> out = simpleJdbcCall.execute(in);
/*** Convert to JSONObjects ***/
JSONObject jsonRes = new JSONObject();
jsonRes.put("body", out.get("#result-set-1"));
System.out.println(out.get("#result-set-1"));
output :
[{user_id=484, user_name="abc", email=null, contact_no=123456789},
{user_id=485, user_name=xyz, email=null, contact_no=235612354}]
Expected output :
{
"body":
"Data":{
{
{user_id=484, user_name="abc", email=null, contact_no=123456789},
{user_id=485, user_name=xyz, email=null, contact_no=235612354}
}
}
}
Try using HashMap You can nest as many elements(HashMaps) as you want.尝试使用 HashMap 您可以嵌套任意数量的元素(HashMap)。 Here is an example
这是一个例子
Map<String, Object> out = simpleJdbcCall.execute(in);
Map<String, Object> users = new HashMap<String, Object>();
users.put( "0", out.get("#result-set-1") );
Map<String, Object> data = new HashMap<String, Object>();
data.put( "Data", users );
Map<String, Object> body = new HashMap<String, Object>();
body.put( "body", data );
JSONObject json = new JSONObject();
json.putAll( body );
System.out.printf( "JSON: %s", json.toString(2) );
In your last line, print jsonRes
instead of out.get("#result-set-1")
:在最后一行,打印
jsonRes
而不是out.get("#result-set-1")
:
System.out.println(jsonRes);
Then you will see something closer to what you expect, probably pretty similar to:然后你会看到一些更接近你期望的东西,可能非常类似于:
{
"body": [
{user_id=484, user_name="abc", email=null, contact_no=123456789},
{user_id=485, user_name=xyz, email=null, contact_no=235612354}
]
}
If it works out like this, then body
is the JsonArray
如果结果是这样,那么
body
就是JsonArray
You can also use ObjectMapper(Jackson)您也可以使用 ObjectMapper(Jackson)
String output = <Stored_Procedure_Output>;
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.readValue(output, ArrayNode.class);
for(int i=0;i<arrayNode.size;i++){
JsonNode obj = arrayNode.get(i);
// You can use the obj to retrieve each object
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.