search
HomeJavajavaTutorialHow to convert Json to List, Map and entity into each other in Java

第一步:导入依赖

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>

第二步:开始使用

场景一:转换普通对象(Bean)。

1.将普通的JavaBean转换为Json字符串是最常用的操作了,首先创建一个简单的类,例如:Person。

public class Person
{
    private String name;
    private int age;
    private boolean isMale;
    private List<String> hobbies;

    // 省略构造器和getter/setter方法,注意重写toString方法,便于查看控制台输出。

    @Override
    public String toString()
    {
        final StringBuilder sb = new StringBuilder("Person{");
        sb.append("name=&#39;").append(name).append(&#39;\&#39;&#39;);
        sb.append(", age=").append(age);
        sb.append(", isMale=").append(isMale);
        sb.append(", hobbies=").append(hobbies);
        sb.append(&#39;}&#39;);
        return sb.toString();
    }
}

2.使用Gson解析Person的实例。

    1  先创建Person对象。
    2  在创建Gson对象。
    3  调用Gson的String toJson(Object)方法,来将对象转换为json字符串。

@Test
public void testBeanToJson()
{
    // 创建Bean
    Person p = new Person("艾伦·耶格尔", 16, true, Arrays.asList("自由", "迫害莱纳"));
    // 创建Gson对象
    Gson gson = new Gson();
    // 调用Gson的String toJson(Object)方法将Bean转换为json字符串
    String pJson = gson.toJson(p);

    System.out.println(pJson);
    // {"name":"艾伦·耶格尔","age":16,"isMale":true,"hobbies":["自由","迫害莱纳"]}
}

3.将Person实例的json字符串转换为Person对象。

调用Gson的 t fromJson(String, Class)方法,将Json串转换为对象

// 调用Gson的 <T> t fromJson(String, Class)方法,将Json串转换为对象
Person person = gson.fromJson(pJson, Person.class);
System.out.println(person);
// Person{name=&#39;艾伦·耶格尔&#39;, age=16, isMale=true, hobbies=[自由, 迫害莱纳]}

使用场景二:转换List集合。

@Test
public void testListToJson()
{
    // 先准备一个List集合
    List<Person> list = new ArrayList<Person>();
    list.add(new Person("三笠·阿克曼", 16, false, Arrays.asList("砍巨人", "保护艾伦")));
    list.add(new Person("阿明·阿诺德", 16, true, Arrays.asList("看书", "玩海螺")));
    System.out.println(list);
    // 创建Gson实例
    Gson gson = new Gson();
    // 调用Gson的toJson方法
    String listJson = gson.toJson(list);
    System.out.println(listJson);
    // [{"name":"三笠·阿克曼","age":16,"isMale":false,"hobbies":["砍巨人","保护艾伦"]},{"name":"阿明·阿诺德","age":16,"isMale":true,"hobbies":["看书","玩海螺"]}]
}

Json转List对象

由于List接口带泛型,如果还调用 t fromJson(String, Class)方法,那么返回的虽然还是个List集合,但是集合里面的数据却不是Person对象,而是Map对象,并将Person属性以键值对的形式存放在Map的实例中。让我们来验证一下。

......// 此处延续以上代码
List fromJson = gson.fromJson(listJson, List.class);
System.out.println(fromJson.get(0).getClass());
// class com.google.gson.internal.LinkedTreeMap

要想获取的List还和之前的一毛一样,那么我们需要调用Gson的 T fromJson(String, Type) 方法。如下:

可以使用Gson包提供的TypeToken类获取Type类型,然后将其作为此方法的参数。这个类带有泛型,且这个泛型就是Json串转换成为对象后的类型(此处是List)我们不需要重写这个类中的任何方法,只需要创建这个类的一个匿名内部类并调用getTpye()方法即可。

注意:一定要将这个匿名内部类的泛型写为Json字符串解析后生成的对象类型。

......// 此处延续以上代码
// 调用Gson的 T fromJson(String, Type)将List集合的json串反序列化为List对象
List<Person> plist = gson.fromJson(listJson, new TypeToken<List<Person>>(){}.getType());
System.out.println(plist);
// [Person{name=&#39;三笠·阿克曼&#39;, age=16, isMale=false, hobbies=[砍巨人, 保护艾伦]}, Person{name=&#39;阿明·阿诺德&#39;, age=16, isMale=true, hobbies=[看书, 玩海螺]}]

使用场景三:转换Map集合。

转换Map的步骤就和转换List的步骤一模一样了,代码如下。详解请看List转换。

@Test
public void testMapToJson()
{
    Map<String, Person> map = new HashMap<>();
    map.put("p1", new Person("利威尔·阿克曼", 35, true, Arrays.asList("砍猴儿", "打扫卫生")));
    map.put("p2", new Person("韩吉·佐耶", 33, false, Arrays.asList("研究巨人", "讲故事")));

    Gson gson = new Gson();
    String mapJson = gson.toJson(map);

    System.out.println(mapJson);
    // {"p1":{"name":"利威尔·阿克曼","age":35,"isMale":true,"hobbies":["砍猴儿","打扫卫生"]},"p2":{"name":"韩吉·佐耶","age":33,"isMale":false,"hobbies":["研究巨人","讲故事"]}}
    Map<String, Person> jsonMap = gson.fromJson(mapJson, new TypeToken<Map<String, Person>>() { }.getType());
    System.out.println(jsonMap);
}

总的来说就是toJson()和fromJson两个方法

The above is the detailed content of How to convert Json to List, Map and entity into each other in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools