json byte array fingerprint example


0 down vote favorite

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??

share | improve this question
 
    
Should your array be inside a string? –  atw13 Mar 26 '13 at 3:05
    
You've got an array containing an object containing an array. You first need to index the array, then extract element "fingerprint" from the resulting object. The "fingerprint" element will be an array which is presumably the byte array you want. –  Hot Licks Mar 26 '13 at 3:24
    
But @atw13 has a point that the "fingerprint" element is apparently a String containing the array, so you need to extract the String, then run that through the JSON interpreter to extract the array. –  Hot Licks Mar 26 '13 at 3:25
add comment

1 Answer

active oldest votes
up vote 2 down vote accepted

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!

你可能感兴趣的:(json byte array fingerprint example)