java - 将 JSON 字符串转换为 Java 对象 : Java

标签 java json gson

我有一个字符串

String aString = "[{code:32022,estCode:0,timeZone:CE},{code:59400,estCode:0,timeZone:CE},{code:59377,estCode:0,timeZone:CE},{code:59525,estCode:0,timeZone:CE},{code:59560,estCode:0,timeZone:CE}]"

我正在尝试使用 gson 将此字符串转换为 Map[]

我尝试使用

Gson gsn = new GsonBuilder().create();
Map[] b = gsn.fromJson(aString , Map[].class);

我能够正确解析它,并且输出为

[{code=32022.0, estCode=0.0, timeZone=CE}, {code=59400.0, estCode=0.0, timeZone=CE}, {code=59377.0, estCode=0.0, timeZone=CE}, {code=59525.0, estCode=0.0, timeZone=CE}, {code=59560.0, estCode=0.0, timeZone=CE}]

但是这些值被转换为 double ,我需要它作为字符串。 例如:32022 转换为 32022.0 我需要它,因为 32022 有什么方法可以在 gson 中使用 ExclusionStrategy 来实现。我在 ExclusionStrategy、shouldSkipClass 和 shouldSkipField 中只看到两种可用的方法,还有其他方法可以使用 gson 来实现吗?

请帮忙

最佳答案

无法更改值的类型,但您可以使用自己的类,如下所示:

public static void main(String[] args) {
        String aString = "[{code:32022,estCode:0,timeZone:CE},{code:59400,estCode:0,timeZone:CE},{code:59377,estCode:0,timeZone:CE},{code:59525,estCode:0,timeZone:CE},{code:59560,estCode:0,timeZone:CE}]";
        Gson gsn = new GsonBuilder().create();
        TimeCode[] b =  gsn.fromJson(aString, TimeCode[].class);
        for(TimeCode entry:b){
                System.out.print(entry+",");
        }

    }

    class TimeCode{
        String code;
        String estCode;
        String timeZone;

        public String toString(){
            return "code="+code+",estCode="+estCode+",timeZone="+timeZone;
        }
    }

输出:

code=32022,estCode=0,timeZone=CE,code=59400,estCode=0,timeZone=CE,code=59377,estCode=0,timeZone=CE,code=59525,estCode=0,timeZone=CE,code=59560,estCode=0,timeZone=CE,

希望对您有所帮助。

关于java - 将 JSON 字符串转换为 Java 对象 : Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34675671/

相关文章:

android - 从字符串转换为 JSON 对象 Android

java - 仅当未设置时才排除 SerializedName 字段

java - GSON - 人类可读性

java - 以编程方式更改 ImageView 大小

json - shell脚本中的jq : parse argument with '-'

javascript - 正确解析 YouTube API 的响应

java - 如何让 Gson 的单转义与 Javascript 的特殊字符和符号的双转义一起使用?

java - 我想知道运行 java selenium 代码所需的版本

java - 滚动 3d 球的旋转

java - 我的构建器对象的实现有哪些缺点?