我是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课程:
public class PatientJson {
String id,sampleId,gender;
//with all the three getter and setters.
}
答案 0 :(得分:1)
我希望它会对你有所帮助..!
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 :(得分:0)
您需要更改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);