Extract byte array from JSON

I have JSON in 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 am trying to extract an array of bytes from it using the following:

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

Where is JSONFingerprint:

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

I get 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 anyone have any ideas?

+1
source share
1 answer

It seems your JSON and POJO do not match. There can be 2 possible solutions for this.

Solution 1: -

If you cannot change the JSON format (i.e. your JSON will be like 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 the JSONFingerprint class to the following: -

 public class JSONFingerprint { String fingerprint; public String getfingerprintData() { return fingerprint; } } 

and you need to JSON your JSON as follows: -

 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 will be like this,

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

Then you will have to change the JSON to the following: -

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

which you can usually analyze, as you have already done: -

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

Hope this helps you!

+3
source

Source: https://habr.com/ru/post/974418/


All Articles