栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从LinkedHashMap构建有序的JSON字符串

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从LinkedHashMap构建有序的JSON字符串

格森,
如果你的朋友。这会将有序地图打印到有序JSON字符串中。

如果要保留插入顺序,请使用

linkedHashMap

我使用了最新版本的Gson(2.8.5),可以通过本文底部的以下选项下载它。

    import java.util.*;    import com.google.gson.Gson;    public class OrderedJson {        public static void main(String[] args) { // Create a new ordered map. Map<String,String> mylinkedHashMap = new linkedHashMap<String, String>(); // 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"}        }    }

如果您希望将项目始终插入正确的位置,请改用a

TreeMap

    import java.util.*;    import com.google.gson.Gson;    public class OrderedJson {        public static void main(String[] args) { // Create a new ordered map. Map<String,String> myTreeHashMap = new TreeMap<String, String>(); // Add items, in any order, to the map. myTreeHashMap.put("3", "third"); myTreeHashMap.put("1", "first"); myTreeHashMap.put("2", "second"); // Instantiate a new Gson instance. Gson gson = new Gson(); // Convert the ordered map into an ordered string. String json = gson.toJson(myTreeHashMap, TreeMap.class); // Print ordered string. System.out.println(json); // {"1":"first","2":"second","3":"third"}        }    }

依赖选项

马文

<dependency>    <groupId>com.google.pre.gson</groupId>    <artifactId>gson</artifactId>    <version>2.8.5</version></dependency>

摇篮

compile 'com.google.pre.gson:gson:2.8.5'

或者,您可以访问Maven
Central
以获得更多下载选项。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/508605.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号