热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

将JSON数组解析为java.util。列表与Gson-ParsingJSONarrayintojava.util.ListwithGson

IhaveaJsonObjectnamedmappingwiththefollowingcontent:我有一个名为“mapping”的JsonObject,内容如下:{

I have a JsonObject named "mapping" with the following content:

我有一个名为“mapping”的JsonObject,内容如下:

{
    "client": "127.0.0.1",
    "servers": [
        "8.8.8.8",
        "8.8.4.4",
        "156.154.70.1",
        "156.154.71.1"
    ]
}

I know I can get the array "servers" with:

我知道我可以用:

mapping.get("servers").getAsJsonArray()

And now I want to parse that JsonArray into a java.util.List...

现在我要把这个JsonArray解析为java.util.List…

What is the easiest way to do this?

最简单的方法是什么?

5 个解决方案

#1


213  

Definitely the easiest way to do that is using Gson's default parsing function fromJson().

最简单的方法就是使用Gson的默认解析函数fromJson()。

There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType (e.g., any List), which is fromJson(JsonElement json, Type typeOfT).

这个函数的实现适用于当您需要反序列化为任何参数类型(例如,任何列表)时,它是fromJson(JsonElement json,类型typeOfT)。

In your case, you just need to get the Type of a List and then parse the JSON array into that Type, like this:

在您的示例中,只需获取列表 的类型,然后将JSON数组解析为该类型,如下所示:

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;

JsonElement yourJson = mapping.get("servers");
Type listType = new TypeToken>() {}.getType();

List yourList = new Gson().fromJson(yourJson, listType);

In your case yourJson is a JsonElement, but it could also be a String, any Reader or a JsonReader.

在您的例子中,您的json是一个JsonElement,但它也可以是一个字符串、任何读取器或JsonReader。

You may want to take a look at Gson API documentation.

您可能想看看Gson API文档。

#2


16  

Below code is using com.google.gson.JsonArray. I have printed the number of element in list as well as the elements in List

下面的代码使用com.google.gson.JsonArray。我已经打印了列表中的元素数量以及列表中的元素

import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;


public class Test {

    static String str = "{ "+ 
            "\"client\":\"127.0.0.1\"," + 
            "\"servers\":[" + 
            "    \"8.8.8.8\"," + 
            "    \"8.8.4.4\"," + 
            "    \"156.154.70.1\"," + 
            "    \"156.154.71.1\" " + 
            "    ]" + 
            "}";

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {

            JsonParser jsOnParser= new JsonParser();
            JsonObject jo = (JsonObject)jsonParser.parse(str);
            JsonArray jsOnArr= jo.getAsJsonArray("servers");
            //jsonArr.
            Gson googleJson = new Gson();
            ArrayList jsOnObjList= googleJson.fromJson(jsonArr, ArrayList.class);
            System.out.println("List size is : "+jsonObjList.size());
                    System.out.println("List Elements are  : "+jsonObjList.toString());


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

OUTPUT

输出

List size is : 4

List Elements are  : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]

#3


1  

I read solution from official website of Gson at here

我在这里阅读了Gson官方网站的解决方案

And this code for you:

这是你的密码:

    String json = "{"client":"127.0.0.1","servers":["8.8.8.8","8.8.4.4","156.154.70.1","156.154.71.1"]}";

    JsonObject jsOnObject= new Gson().fromJson(json, JsonObject.class);
    JsonArray jsOnArray= jsonObject.getAsJsonArray("servers");

    String[] arrName = new Gson().fromJson(jsonArray, String[].class);

    List lstName = new ArrayList<>();
    lstName = Arrays.asList(arrName);

    for (String str : lstName) {
        System.out.println(str);
    }    

Result show on monitor:

监测结果表明:

8.8.8.8
8.8.4.4
156.154.70.1
156.154.71.1

#4


0  

I was able to get the list mapping to work with just using @SerializedName for all fields.. no logic around Type was necessary.

我可以使用@SerializedName为所有字段进行列表映射。没有逻辑围绕类型。

Running the code - in step #4 below - through the debugger, I am able to observe that the List mGalleryImages object populated with the JSON data

通过调试器运行代码—在第4步—通过调试器,我可以看到列表 mGalleryImages对象填充了JSON数据。

Here's an example:

这里有一个例子:

1. The JSON

1。JSON

   {
    "name": "Some House",
    "gallery": [
      {
        "description": "Nice 300sqft. den.jpg",
        "photo_url": "image/den.jpg"
      },
      {
        "description": "Floor Plan",
        "photo_url": "image/floor_plan.jpg"
      }
    ]
  }

2. Java class with the List

2。带有列表的Java类

public class FocusArea {

    @SerializedName("name")
    private String mName;

    @SerializedName("gallery")
    private List mGalleryImages;
}

3. Java class for the List items

3所示。列表项的Java类。

public class ContentImage {

    @SerializedName("description")
    private String mDescription;

    @SerializedName("photo_url")
    private String mPhotoUrl;

    // getters/setters ..
}

4. The Java code that processes the JSON

4所示。处理JSON的Java代码

    for (String key : focusAreaKeys) {

        JsonElement sectiOnElement= sectionsJsonObject.get(key);
        FocusArea focusArea = gson.fromJson(sectionElement, FocusArea.class);
    }

#5


-2  

Check this out, I believe this is what you need.

看看这个,我相信这就是你需要的。

public class Test {
public static void main(String[] args) {
    //  this part is just to create the JSON object in question, so I am sure you are already having it.
    JsonObject mappings = new JsonObject();
    JsonElement e = new JsonPrimitive("127.0.0.1");
    mappings.add("client", e);

    JsonArray servers = new JsonArray();
    JsonElement s1 = new JsonPrimitive("8.8.8.8");
    JsonElement s2 = new JsonPrimitive("8.8.4.4");
    JsonElement s3 = new JsonPrimitive("156.154.70.1");
    JsonElement s4 = new JsonPrimitive( "156.154.71.1");
    servers.add(s1);
    servers.add(s2);
    servers.add(s3);
    servers.add(s4);

    mappings.add("servers", servers);

    // json creation ends.

    // split the resultant string based on comma and then convert the resultant array into a list.  
    String[] split = mappings.get("servers").getAsJsonArray().toString().split(",");
    List myList = new ArrayList();
    Collections.addAll(myList, split);

    // again the following part is to demonstrate that the strings were populated in the list.
    for(String l : myList){
        System.out.println(l);
    }
}
}

推荐阅读
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • 第四章高阶函数(参数传递、高阶函数、lambda表达式)(python进阶)的讲解和应用
    本文主要讲解了第四章高阶函数(参数传递、高阶函数、lambda表达式)的相关知识,包括函数参数传递机制和赋值机制、引用传递的概念和应用、默认参数的定义和使用等内容。同时介绍了高阶函数和lambda表达式的概念,并给出了一些实例代码进行演示。对于想要进一步提升python编程能力的读者来说,本文将是一个不错的学习资料。 ... [详细]
  • 如何查询zone下的表的信息
    本文介绍了如何通过TcaplusDB知识库查询zone下的表的信息。包括请求地址、GET请求参数说明、返回参数说明等内容。通过curl方法发起请求,并提供了请求示例。 ... [详细]
  • 本文介绍了如何使用JSONObiect和Gson相关方法实现json数据与kotlin对象的相互转换。首先解释了JSON的概念和数据格式,然后详细介绍了相关API,包括JSONObject和Gson的使用方法。接着讲解了如何将json格式的字符串转换为kotlin对象或List,以及如何将kotlin对象转换为json字符串。最后提到了使用Map封装json对象的特殊情况。文章还对JSON和XML进行了比较,指出了JSON的优势和缺点。 ... [详细]
  • 目录实现效果:实现环境实现方法一:基本思路主要代码JavaScript代码总结方法二主要代码总结方法三基本思路主要代码JavaScriptHTML总结实 ... [详细]
  • 本文介绍了Redis的基础数据结构string的应用场景,并以面试的形式进行问答讲解,帮助读者更好地理解和应用Redis。同时,描述了一位面试者的心理状态和面试官的行为。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • JavaSE笔试题-接口、抽象类、多态等问题解答
    本文解答了JavaSE笔试题中关于接口、抽象类、多态等问题。包括Math类的取整数方法、接口是否可继承、抽象类是否可实现接口、抽象类是否可继承具体类、抽象类中是否可以有静态main方法等问题。同时介绍了面向对象的特征,以及Java中实现多态的机制。 ... [详细]
  • 本文介绍了使用PHP实现断点续传乱序合并文件的方法和源码。由于网络原因,文件需要分割成多个部分发送,因此无法按顺序接收。文章中提供了merge2.php的源码,通过使用shuffle函数打乱文件读取顺序,实现了乱序合并文件的功能。同时,还介绍了filesize、glob、unlink、fopen等相关函数的使用。阅读本文可以了解如何使用PHP实现断点续传乱序合并文件的具体步骤。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 摘要: 在测试数据中,生成中文姓名是一个常见的需求。本文介绍了使用C#编写的随机生成中文姓名的方法,并分享了相关代码。作者欢迎读者提出意见和建议。 ... [详细]
  • Week04面向对象设计与继承学习总结及作业要求
    本文总结了Week04面向对象设计与继承的重要知识点,包括对象、类、封装性、静态属性、静态方法、重载、继承和多态等。同时,还介绍了私有构造函数在类外部无法被调用、static不能访问非静态属性以及该类实例可以共享类里的static属性等内容。此外,还提到了作业要求,包括讲述一个在网上商城购物或在班级博客进行学习的故事,并使用Markdown的加粗标记和语句块标记标注关键名词和动词。最后,还提到了参考资料中关于UML类图如何绘制的范例。 ... [详细]
  • 本文介绍了一种轻巧方便的工具——集算器,通过使用集算器可以将文本日志变成结构化数据,然后可以使用SQL式查询。集算器利用集算语言的优点,将日志内容结构化为数据表结构,SPL支持直接对结构化的文件进行SQL查询,不再需要安装配置第三方数据库软件。本文还详细介绍了具体的实施过程。 ... [详细]
  • 本文介绍了一个Python函数same_set,用于判断两个相等长度的数组是否包含相同的元素。函数会忽略元素的顺序和重复次数,如果两个数组包含相同的元素,则返回1,否则返回0。文章还提供了函数的具体实现代码和样例输入输出。 ... [详细]
author-avatar
战冰_斗雪
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有