从JSON中提取字节数组

时间:2013-03-26 03:00:47

标签: java json bytearray gson illegalstateexception

我有以下格式的JSON:

[{"fingerprint":"[79,0,0,0,18,0,0,0,18,0,0,0,19,0,0,0,23,0,0,0,40,0,0,0,42,0,0,0,63,0,0,0,68,0,0,0,71,0,....]"}]

我一直在尝试使用以下方法从中提取字节数组:

JSONFingerprint fingerprintData = gson.fromJson(obj, JSONFingerprint.class);

JSONFingerprint在哪里:

public class JSONFingerprint {

    byte[] fingerprint;

    public byte[] getfingerprintData() {
        return fingerprint;
    }

}

我收到了这个错误:

Exception in thread "Thread-0" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
    at com.google.gson.Gson.fromJson(Gson.java:795)
    at com.google.gson.Gson.fromJson(Gson.java:859)
    at com.google.gson.Gson.fromJson(Gson.java:832)

有人有任何想法吗?

1 个答案:

答案 0 :(得分:3)

您的 JSON POJO 似乎不匹配。可能有两种可能的解决方案。

解决方案1: -

如果您无法更改JSON格式(即)您的JSON将会是这样,

[{"fingerprint":"[79,0,0,0,18,0,0,0,18,0,0,0,19,0,0,0,23,0,0,0,40,0,0,0,42,0,0,0,63,0,0,0,68,0,0,0,71,0,....]"}]

然后您需要将JSONFingerprint课改为: -

public class JSONFingerprint {

    String fingerprint;

    public String getfingerprintData() {
        return fingerprint;
    }
}

您需要像这样解析JSON: -

JSONFingerprint[] dummy = new JSONFingerprint[0]; 
JSONFingerprint[] fingerPrint = gson.fromJson(json, dummy.getClass());
System.out.println(fingerPrint[0].getfingerprintData());

解决方案2: -

如果您的POJO无法更改(即)您的POJO将会是这样,

public class JSONFingerprint {

    byte[] fingerprint;

    public byte[] getfingerprintData() {
        return fingerprint;
    }
}

然后,您必须将JSON格式更改为以下内容: -

{"fingerprint":[1,2,3,4,5,6,7,8,9,10]}

你可以解析它,正如你已经完成的那样: -

JSONFingerprint fingerprintData = gson.fromJson(obj, JSONFingerprint.class);

希望这能帮到你!