001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.wicket.ajax.json; 018 019import java.util.List; 020import java.util.Map; 021 022import com.github.openjson.JSONArray; 023import com.github.openjson.JSONException; 024import com.github.openjson.JSONObject; 025 026/** 027 * @since 6.0.0 028 */ 029public final class JsonUtils 030{ 031 private JsonUtils() 032 {} 033 034 /** 035 * Converts a Map to JSONArray suitable for jQuery#param(). 036 * 037 * @param map 038 * the map with key/value(s) 039 * @return a JSONArray that contains JSONObject's with name/value pairs 040 * @throws JSONException 041 */ 042 public static JSONArray asArray(Map<String, Object> map) throws JSONException 043 { 044 JSONArray jsonArray = new JSONArray(); 045 046 if (map != null) 047 { 048 for (Map.Entry<String, Object> entry : map.entrySet()) 049 { 050 String name = entry.getKey(); 051 Object value = entry.getValue(); 052 if (value instanceof List) { 053 List<?> values = (List<?>) value; 054 for (Object v : values) 055 { 056 if (v != null) 057 { 058 JSONObject object = new JSONObject(); 059 object.put("name", name); 060 object.put("value", v); 061 jsonArray.put(object); 062 } 063 } 064 } 065 else if (value != null) 066 { 067 if (value.getClass().isArray()) 068 { 069 Object[] array = (Object[]) value; 070 for (Object v : array) 071 { 072 if (v != null) 073 { 074 JSONObject object = new JSONObject(); 075 object.put("name", name); 076 object.put("value", v); 077 jsonArray.put(object); 078 } 079 } 080 } 081 else 082 { 083 JSONObject object = new JSONObject(); 084 object.put("name", name); 085 object.put("value", value); 086 jsonArray.put(object); 087 } 088 } 089 } 090 } 091 092 return jsonArray; 093 } 094}