[英]Java Json Object to Json Array Conversion
我是 java 的新手。我正在尝试从存储过程中获取数据并将其转换为 json 数组。 但是我的代码面临一些问题。
/*** 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}
}
}
}
尝试使用 HashMap 您可以嵌套任意数量的元素(HashMap)。 这是一个例子
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) );
在最后一行,打印jsonRes
而不是out.get("#result-set-1")
:
System.out.println(jsonRes);
然后你会看到一些更接近你期望的东西,可能非常类似于:
{
"body": [
{user_id=484, user_name="abc", email=null, contact_no=123456789},
{user_id=485, user_name=xyz, email=null, contact_no=235612354}
]
}
如果结果是这样,那么body
就是JsonArray
您也可以使用 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.