使用 gson/jackson java API 解析 json 文件

parse json file using gson/jackson java API

我是 JSON 和 GSON 的新蜜蜂。我的 JSON 结构如下所述,我正在使用 gson 库解析 json 对象并检索我从 getter 获取所有空值的值。谁能帮我解决这个问题。

JSON 文件:

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

Java-gson代码:

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 class:

public class PatientJson {
    String id,sampleId,gender;
//with all the three getter and setters.
}

您需要如下更改您的PatientJson

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

基本上变量的名称应该与您在 json 中的名称相同,或者您必须使用 SerializedName REF 将变量映射到 json 参数以下

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.
}

要从样本中获取数据json,您需要执行以下操作

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);

希望对您有所帮助..!

    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;

}