我想在JSON结构中发送2D数组。
我想要的总体结构是
{
"PED": {
"fun": "enviarPedido",
"txtUser":"123",
"md5Passwd": "123",
"arrArticulos": [
[50,10,5,50],
[51,9,6.5,58.5],
[52,8,7,56],
[53,7,8.5,59.5]
]
}
}我希望从游标数据生成2D数组并放入这个JSON结构中
"arrArticulos": [
[50,10,5,50],
[51,9,6.5,58.5],
[52,8,7,56],
[53,7,8.5,59.5]
]解决办法是什么?
发布于 2013-12-17 21:27:50
这个代码:
JSONObject PED = new JSONObject();
PED.put( "fun", "enviarPedido" );
PED.put( "txtUser", "123" );
PED.put( "md5Passwd", "123" );
JSONArray articulos1 = new JSONArray();
articulos1.put( 50 );
articulos1.put( 10 );
articulos1.put( 5 );
articulos1.put( 50 );
JSONArray articulos2 = new JSONArray();
articulos2.put( 51 );
articulos2.put( 9 );
articulos2.put( 6.5 );
articulos2.put( 58.5 );
JSONArray articulos3 = new JSONArray();
articulos3.put( 52 );
articulos3.put( 8 );
articulos3.put( 7 );
articulos3.put( 56 );
JSONArray articulos4 = new JSONArray();
articulos4.put( 51 );
articulos4.put( 9 );
articulos4.put( 6.5 );
articulos4.put( 58.5 );
JSONArray arrArticulos = new JSONArray();
arrArticulos.put( articulos1 );
arrArticulos.put( articulos2 );
arrArticulos.put( articulos3 );
arrArticulos.put( articulos4 );
PED.put( "arrArticulos", arrArticulos );
JSONObject body = new JSONObject();
body.put( "PED", PED );
String json = body.toString();将生成以下字符串:
{
"PED": {
"arrArticulos": [
[
50,
10,
5,
50
],
[
51,
9,
6.5,
58.5
],
[
52,
8,
7,
56
],
[
51,
9,
6.5,
58.5
]
],
"md5Passwd": "123",
"txtUser": "123",
"fun": "enviarPedido"
}
}发布于 2022-08-31 11:20:54
你可以简单地做逆向工程。将Json字符串解析为Map<String,Object>,如果您使用Json库将Json字符串写为Json,则该映射将为您提供Json字符串。您可以使用Jackson库或Gson库或任何其他可用的库。下面是我为执行我刚才建议的代码而编写的代码:
private static void jsonParserTest() {
try {
String jsonStr = "{\n" +
" \"PED\": {\n" +
" \"fun\": \"enviarPedido\",\n" +
" \"txtUser\":\"123\",\n" +
" \"md5Passwd\": \"123\", \n" +
" \"arrArticulos\": [\n" +
" [50,10,5,50],\n" +
" [51,9,6.5,58.5],\n" +
" [52,8,7,56],\n" +
" [53,7,8.5,59.5]\n" +
" ]\n" +
" }\n" +
"}";
Map<String, Object> map = JsonUtils.readObjectFromJsonString(jsonStr, Map.class);
System.out.println(map);
System.out.println(JsonUtils.writeObjectToJsonString(map));
} catch (IOException e) {
e.printStackTrace();
}
}这是输出:
{PED={fun=enviarPedido, txtUser=123, md5Passwd=123, arrArticulos=[[50, 10, 5, 50], [51, 9, 6.5, 58.5], [52, 8, 7, 56], [53, 7, 8.5, 59.5]]}}
{"PED":{"fun":"enviarPedido","txtUser":"123","md5Passwd":"123","arrArticulos":[[50,10,5,50],[51,9,6.5,58.5],[52,8,7,56],[53,7,8.5,59.5]]}}因此,如果您创建了一个在输出的第一行中描述的Map,然后将其序列化为JSON,那么您将得到您想要的JSON --在我的示例中使用的类JsonUtils是Jackson库上的一个非常薄的包装器,但使用起来非常简单。它是由我编写和维护的开源MgntUtils库的一部分。这是一个JsonUtils类的Javadoc。如果您想使用MgntUtils库,可以在Maven central或Github上找到它的Maven伪影 (附带源代码和Javadoc)。
https://stackoverflow.com/questions/20641122
复制相似问题