Reputation: 6968
I have a JSON of the following format:
[{"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,....]"}]
I have been trying to extract the byte array from it using the following:
JSONFingerprint fingerprintData = gson.fromJson(obj, JSONFingerprint.class);
Where JSONFingerprint is:
public class JSONFingerprint {
byte[] fingerprint;
public byte[] getfingerprintData() {
return fingerprint;
}
}
I have been getting this error:
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)
Does anybody have any ideas??
Upvotes: 2
Views: 8683
Reputation: 45070
It seems your JSON and POJO don't match. There can be 2 possible solutions for this.
Solution 1:-
If you cannot change the JSON format(i.e.)your JSON is gonna be this,
[{"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,....]"}]
Then you need to change your JSONFingerprint
class to this:-
public class JSONFingerprint {
String fingerprint;
public String getfingerprintData() {
return fingerprint;
}
}
and you need to parse your JSON
like this:-
JSONFingerprint[] dummy = new JSONFingerprint[0];
JSONFingerprint[] fingerPrint = gson.fromJson(json, dummy.getClass());
System.out.println(fingerPrint[0].getfingerprintData());
Solution 2:-
If your POJO cannot change(i.e.)your POJO is gonna be this,
public class JSONFingerprint {
byte[] fingerprint;
public byte[] getfingerprintData() {
return fingerprint;
}
}
Then you'll have to change your JSON
format to something like this:-
{"fingerprint":[1,2,3,4,5,6,7,8,9,10]}
which you can parse it usually, as you've already done:-
JSONFingerprint fingerprintData = gson.fromJson(obj, JSONFingerprint.class);
Hope this helps you!
Upvotes: 3