Gson -解析字段为数组或字符串的json

t3psigkw  于 2022-11-06  发布在  其他
关注(0)|答案(3)|浏览(214)

我试图用Gson解析一些json,但遇到以下问题:
这是我的Json:

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

这是我的java类:

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;
    }

}

如何让Gson解析它并始终将value作为String数组使用?

qco9c6ql

qco9c6ql1#

我的建议如下:
第1步:请对Decode类进行以下小修改。
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 + "]";
 }

}

步骤2:请创建以下JsonDeserializer
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;
 }

}

步骤3:现在是时候deserialize您的json了,如下所示:
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));
  }

 }
bnlyeluc

bnlyeluc2#

json的格式不正确,它应该是:

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

同样,您的解析器类应该是:

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;
    }

}

希望能有所帮助:)

vjhs03f7

vjhs03f73#

我遇到了同样的问题,但是返回的json结果更复杂,我只是将那些类型不确定的字段定义为Object类型,在getter方法中进行了一点处理。

public class POI {
    @SerializedName("address")
    private Object rawAddress;
    @SerializedName("tel")
    private Object rawTel;

    //    these two variables are used, parsed from rawXXX
    private ArrayList<String> addresses;
    private ArrayList<String> tels;

    public ArrayList<String> getAddresses() {
        if (null == addresses) {
            addresses = new ArrayList<>();
            if (rawAddress instanceof ArrayList<?>) {
                for (Object o : (ArrayList<?>) rawAddress) {
                    if (o instanceof String) {
                        addresses.add((String) o);
                    }
                }
            } else if (rawAddress instanceof String) {
                addresses.add((String) rawAddress);
            }
        }
        return addresses;
    }

    public ArrayList<String> getTels() {
        if (null == tels) {
            tels = new ArrayList<>();
            if (rawTel instanceof ArrayList<?>) {
                for (Object o : (ArrayList<?>) rawTel) {
                    if (o instanceof String) {
                        tels.add((String) o);
                    }
                }
            } else if (rawTel instanceof String) {
                tels.add((String) rawTel);
            }
        }
        return tels;
    }

    public Object getRawAddress() {
        return rawAddress;
    }

    public void setRawAddress(Object rawAddress) {
        this.rawAddress = rawAddress;
    }

    public Object getRawTel() {
        return rawTel;
    }

    public void setRawTel(Object rawTel) {
        this.rawTel = rawTel;
    }
}

希望对你有所帮助。

相关问题