Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG]JSON parse 将map解析成Java对象与将json字符串转换成Java对象的功能表现不一致 #3134

Closed
Linindoo opened this issue Oct 25, 2024 · 1 comment
Labels
bug Something isn't working fixed
Milestone

Comments

@Linindoo
Copy link

问题描述

简要描述您碰到的问题。
JSON将map转成Java对象出现类型转换未达预期的问题

环境信息

请填写以下信息:

  • OS信息: win11
  • JDK信息: OpenJdk17.0.1
  • 版本信息:Fastjson2 2.0.53

重现步骤

image

public class Main {
    public static void main(String[] args) {
        String json = "{\"name\":\"希望小学\",\"students\":{\"age\":\"12\",\"id\":\"1\",\"name\":\"张宇\"}}";
        School schoolOne = JSON.parseObject(json, School.class);
        JSONObject schoolTwo = JSON.parseObject(json);
        School schoolThree = schoolTwo.toJavaObject(School.class);
        JSONObject studentOne = schoolTwo.getJSONObject("students");
        JSONArray studentTwo = schoolTwo.getJSONArray("students");
        System.out.println(studentTwo.toString());
    }
    @Data
    private static class School{
        private String name;
        private List<Student> students;
    }
    
    @Data
    private static class Student{
        private String name;

        private String id;

        private String age;
    }
}

期待的正确结果

对于fastjson能够将对象根据目标类型自动转换成array我是认可的,希望能够保留这个特性,对于那些不期望这个特性的可以加一个参数允许关闭这个特性。
说回正题,如图所示schoolOne ,schoolTwo ,studentOne 和studentTwo 是符合预期的转换,但是schoolThree 却未达到预期,经过转换后内部的students数据丢失了,数组大小为0,期望的结果是能够根据目标类型,将map转成对象数组。
如果这个功能一开始就不支持也就罢了,经过测试,json字符串直接解析是可以正常转换,而通过map进行转换缺不能达到预期,希望二者能够保持一致

@Linindoo Linindoo added the bug Something isn't working label Oct 25, 2024
@wenshao wenshao added this to the 2.0.54 milestone Nov 2, 2024
@wenshao wenshao added the fixed label Jan 1, 2025
@wenshao
Copy link
Member

wenshao commented Jan 12, 2025

https://github.com/alibaba/fastjson2/releases/tag/2.0.54
问题已修复,请用新版本

@wenshao wenshao closed this as completed Jan 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working fixed
Projects
None yet
Development

No branches or pull requests

2 participants