简体   繁体   English

Gson - 使用数组或字符串字段解析 json

[英]Gson - parsing json with field that is array or string

I'm trying to parse some json with Gson and I have following problem:我正在尝试用 Gson 解析一些 json 并且我遇到以下问题:

This is my json:这是我的 json:

[{
  "label": "Check Digit",
  "value": "W"
},
{
  "label": "Equipment",
  "value": [
    "With Standard Liftgate",
    "(-) Version Packages"
  ]
}]

This is my java class:这是我的 java class:

public class Decode {

    private String label;
    private List<String> value = new ArrayList<>();

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public List<String> getValue() {
        return value;
    }

    public void setValue(List<String> value) {
        this.value = value;
    }

}

How to make Gson to parse it and use value as Array of String always?如何使 Gson 解析它并始终将value用作字符串数组?

My suggestion is as follows:- 我的建议如下: -

Step 1: Please make following little changes to your Decode class. 第1步:请对您的Decode类进行以下少量更改。

Decode.java Decode.java

import java.util.ArrayList;
import java.util.List;

public class Decode {

private String label;
private List<String> values = new ArrayList<>(); // in json it is "value"

public String getLabel() {
    return label;
}

public void setLabel(String label) {
    this.label = label;
}

public List<String> getValues() {
    return values;
 }

public void setValues(List<String> values) {
    this.values = values;
 }

@Override
public String toString() {
    return "Decode [label=" + label + ", values=" + values + "]";
 }

}

Step 2: Please create following JsonDeserializer . 第2步:请创建以下JsonDeserializer

MyDeserializer.java MyDeserializer.java

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;

public class MyDeserializer implements JsonDeserializer<Decode> {

@Override
public Decode deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
    JsonObject decodeObj = arg0.getAsJsonObject();
    Gson gson = new Gson();
    Decode decode = gson.fromJson(arg0, Decode.class);
    List<String> values = null;
    if (decodeObj.get("value").isJsonArray()) {
        values = gson.fromJson(decodeObj.get("value"), new TypeToken<List<String>>() {
        }.getType());
    } else {
        String single = gson.fromJson(decodeObj.get("value"), String.class);
        values = new ArrayList<String>();
        values.add(single);
    }
    decode.setValues(values);
    return decode;
 }

}

Step 3: Now its time to deserialize your json as follows: 第3步:现在是时候deserialize你的json,如下所示:

GsonMain.java GsonMain.java

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;

import com.google.gson.GsonBuilder;

public class GsonMain{
public static void main(String[] args) throws IOException {
    String filename = "d:/test.json"; // contains the json
    String content = new String(Files.readAllBytes(new File(filename).toPath()));

    GsonBuilder b = new GsonBuilder();
    b.registerTypeAdapter(Decode.class, new MyDeserializer());
    Decode[] array = b.create().fromJson(content, Decode[].class);
    System.out.println(Arrays.toString(array));
  }

 }

The json is not in proper format, it should be : json格式不正确,它应该是:

[{
  "label": "Check Digit",
  "value": ["W"]
},
{
  "label": "Equipment",
  "value": [
    "With Standard Liftgate",
    "(-) Version Packages"
  ]
}]

Again your parser class should be : 你的解析器类应该是:

public class Decode {

    private String label;
    private String[] value;

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public String[] getValue() {
        return value;
    }

    public void setValue(String[] value) {
        this.value = value;
    }

}

Hope it will help :) 希望它会有所帮助:)

I had the same problem, but the returned json results were more complex.我有同样的问题,但返回的 json 结果更复杂。 I just defined those fields with uncertain types as Object type.我只是将那些类型不确定的字段定义为 Object 类型。 Hope to help you.希望能帮到你。

the Decode solution is the cleanest, but if you don't plan on using the model for anything else than deserializing, you could just declare the field as解码解决方案是最干净的,但是如果您不打算将 model 用于反序列化以外的任何其他用途,则可以将该字段声明为

val myField: Any?

and then to read the value:然后读取值:

when (myField) {
    is List<*> -> {}
    is String -> {}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM