For this solution I am using Gson() (you can the jar or the maven dependencies from here) to generate the final string as in your example.
And I have created a couple of helper classes that you could put somewhere else in the project (not necessarily as inner classes).
The main method is just to provide the means of running the code.
The output looks like this:
EDITED I
Original Solution for one b64 item for each float.
{"instances":[{"b64":"QUczMw=="},{"b64":"QgpmZg=="},{"b64":"wgHS8g=="},{"b64":"QU+uFA=="}]}
The code:
public class FloatEncoder {
public static void main(String args[]) {
FloatEncoder encoder = new FloatEncoder();
float [] floats = new float[] {12.45f, 34.6f, -32.456f, 12.98f};
String encodedJson = encoder.encode(floats);
System.out.println(encodedJson);
}
private String encode(float[] floats) {
String rtn;
DataHolder holder = new DataHolder();
String [] audios = convertToBase64Bytes(floats);
for(String audio : audios) {
B64 b64 = new B64();
b64.b64 = audio;
holder.instances.add(b64);
}
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
rtn = gson.toJson(holder);
return rtn;
}
public static String[] convertToBase64Bytes(float[] audio) {
String[] data = new String[audio.length];
for (int i = 0; i < audio.length; i++) {
float amplitude = audio[i];
byte[] byteArray = ByteBuffer.allocate(4).putFloat(amplitude).array();
data[i] = Base64.getEncoder().encodeToString(byteArray);
}
return data;
}
public static class DataHolder{
public ArrayList<B64> instances = new ArrayList<>();
}
public static class B64{
public String b64;
}
}
EDIT II
Solution for one b64 item with the array of floats encoded as a single
string.
{"instances":[{"b64":"QUczM0IKZmbCAdLyQU+uFA=="}]}
The string is the Base64 encoding of a byte array where the first 4 bytes are the first float, the second 4 are the second float and so forth.
public class FloatEncoder {
public static void main(String args[]) {
FloatEncoder encoder = new FloatEncoder();
float [] floats = new float[] {12.45f, 34.6f, -32.456f, 12.98f};
String encodedJson = encoder.encode(floats);
System.out.println(encodedJson);
}
private String encode(float[] floats) {
String rtn;
DataHolder holder = new DataHolder();
String audios = convertToBase64Bytes(floats);
B64 b64 = new B64();
b64.b64 = audios;
holder.instances.add(b64);
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
rtn = gson.toJson(holder);
return rtn;
}
public static String convertToBase64Bytes(float[] audio) {
ByteBuffer byteBuffer = ByteBuffer.allocate(4 * audio.length);
for (int i = 0; i < audio.length; i++) {
float amplitude = audio[i];
byteBuffer.putFloat(amplitude);
}
byte[] data = byteBuffer.array();
String rtn = Base64.getEncoder().encodeToString(data);
return rtn;
}
public static class DataHolder{
public ArrayList<B64> instances = new ArrayList<>();
}
public static class B64{
public String b64;
}
}