从LinkedHashMap构建有序的JSON字符串
我需要按照插入的顺序使用Key / Value对,所以我选择在HashMap
上使用LinkedHashMap
。 但我需要将LinkedHashMap
转换为JSON字符串,其中LinkedHashMap
中的顺序保留在字符串中。
但目前我通过以下方式实现:
- 首先将LinkedHashMap转换为JSON。
-
然后将JSON转换为字符串。
import java.util.LinkedHashMap; import java.util.Map; import org.json.JSONObject; public class cdf { public static void main(String[] args) { Map myLinkedHashMap = new LinkedHashMap(); myLinkedHashMap.put("1","first"); myLinkedHashMap.put("2","second"); myLinkedHashMap.put("3","third"); JSONObject json = new JSONObject(myLinkedHashMap); System.out.println(json.toString()); } }
输出是:
{"3":"third","2":"second","1":"first"} .
但我想按照插入键的顺序,如下所示:
{"1":"first","2":"second","3":"third"}
一旦我将LinkedHashMap
转换为JSON,它就会失去它的顺序(显然JSON没有顺序的概念),因此字符串也是乱序的。 现在,如何生成一个与LinkedHashMap
相同的JSON字符串?
如果你的朋友, 格森 。 这会将有序映射打印为有序的JSON字符串。
我使用了最新版本的Gson(2.3.1),您可以通过本文底部的以下选项下载它。
import java.util.LinkedHashMap; import java.util.Map; import com.google.gson.Gson; public class OrderedJson { public static void main(String[] args) { // Create a new ordered map. Map myLinkedHashMap = new LinkedHashMap(); // Add items, in-order, to the map. myLinkedHashMap.put("1", "first"); myLinkedHashMap.put("2", "second"); myLinkedHashMap.put("3", "third"); // Instantiate a new Gson instance. Gson gson = new Gson(); // Convert the ordered map into an ordered string. String json = gson.toJson(myLinkedHashMap, LinkedHashMap.class); // Print ordered string. System.out.println(json); // {"1":"first","2":"second","3":"third"} } }
依赖选项
Maven的
com.google.code.gson gson 2.3.1
摇篮
compile 'com.google.code.gson:gson:2.3.1'
或者您可以访问Maven Central以获取更多下载选项。
JSONObject
意味着使用org.json
库。 不要那样做; 它是旧的原型,有更好的选择,如jackson和GSON。 有jackson,你只需使用:
String json = new ObjectMapper().writeValueAsString(myLinkedHashMap);
并使用Map使用的任何遍历顺序获取带有条目的JSON字符串。
由于linkedhashmap params而不接受插入顺序的JSON都是字符串。 如下面提到的代码那样将第一个参数改为Integer是没关系的:
Map myLinkedHashMap = new LinkedHashMap<>(); myLinkedHashMap.put(1,"first"); myLinkedHashMap.put(2,"second"); myLinkedHashMap.put(3,"third"); System.out.println(myLinkedHashMap); JSONObject json = new JSONObject(myLinkedHashMap); System.out.println(json.toString());
按字母顺序排序,这是Jackson 2的正确方法。*:
Map myLinkedHashMap = new LinkedHashMap(); myLinkedHashMap.put("1", "first"); myLinkedHashMap.put("2", "second"); myLinkedHashMap.put("3", "third"); ObjectMapper mapper = new ObjectMapper(); mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true); try { System.out.println(mapper.writeValueAsString(myLinkedHashMap)); //prints {"1":"first","2":"second","3":"third"} } catch (JsonProcessingException e) { e.printStackTrace(); }
为有序对创建JsonArray …
JSONArray orderedJson=new JSONArray(); Iterator iterator= ; while (iterator.hasNext()) { Map.Entry me = (Map.Entry)iteratornext(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); JSONObject tmpJson=new JSONObject (); tmpJson.put(me.getKey(),me.getValue());//add key/value to tmpjson orderedJson.add(tmpJson);//add tmpjson to orderedJson }