Parse json file using gson / jackson java API

I am a new bee for both JSON and GSON. My JSON structure is below and I use the gson library to parse the json object and get the values ​​that I get from null values. Can anyone help me on this.

JSON file:

{
   "Samples":[
      {
       "Id":"XX",
       "SampleId":"XX",
       "Gender":"XX"
       }
     ]
}

Java-gson code:

BufferedReader br = new BufferedReader(new FileReader(/mnt/ftp/sample.json));
//convert the json string back to object
patientObj = gson.fromJson(br, PatientJson.class);
patient_id=patientObj.getId();
sample_id=patientObj.getSampleId();
gender=patientObj.getGender();

JSON Patient Class:

public class PatientJson {
    String id,sampleId,gender;
//with all the three getter and setters.
}
+4
source share
2 answers

Hope this helps you!

    JSONObject jsonObject=new JSONObject(readFromFile());  
    JSONArray array= jsonObject.getJSONArray("Samples");  

        JSONObject json=array.getJSONObject(0);  
        PatientJson patient=new PatientJson();  

        patient.setId(json.get("Id"));  
        patient.setSampleId(json.get("SampleId"));  
        patient.setGender(json.get("Gender"));  

 private String readFromFile(){
String ret = "";

try {
InputStream inputStream = openFileInput("yourFile");

if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();

while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}

ret = stringBuilder.toString();

inputStream.close();
}
}
catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "Can not read file: " + e.toString());
}
return ret;

}
+1
source

You need to change PatientJsonbelow

public class PatientJson {
String Id, SampleId, Gender;
//with all the three getter and setters.
}

Basically the variable name should be the same as you get in json, or you need to map the variables to json parameters using the SerializedName REF below

import com.google.gson.annotations.SerializedName;
public class PatientJson {
@SerializedName("Id")
String id;
@SerializedName("SampleId")
String sampleId;
@SerializedName("Gender")
String gender;
//with all the three getter and setters.
}

To get data from your json example, you need to do the following

BufferedReader br = new BufferedReader(new FileReader(/mnt/ftp/sample.json));
  //convert the json string back to object
    Type listType = new TypeToken<ArrayList<PatientJson>>() {}.getType();
    List<PatientJson> patientList = gson.fromJson(br, listType);
0
source

All Articles