我能够解析JSON数据。确切的问题是,我想将学生ID存储在SharedPreference中而不带后缀,即只存储整数?我试图用REGEX拆分JSON值,但不能,因为我没有使用正则表达式。如何解决这个问题?
{
"StdID":S001,
"NAME":"Kirsten Green",
"PHONENO":"095-517-0049",
"DOB":"2009-12-28T00:00:00",
"CLASS":9,
"GENDER":"M",
"ADDRESS":"8254 At Ave",
"NATIONALITY":"Belgium",
"ENROLLEDYEAR":"2016-04-21T00:00:00",
"Photo":null,
"Cat_ID":5,
"base64":null,
"studentDetails":{
"StdID":1,
"GUARDIAN_PHONE_NO":"002-283-4824",
"MOBILE_NO":"1-377-762-8548",
"First_NAME":"Maile",
"Last_Name":"Lancaster",
"Relation":"Father",
"DOB":"2017-02-22T00:00:00",
"Education":"Ph.D",
"Occupation":"Etiam ligula tortor,",
"Income":"20000-30000",
"Email":"urna@sed.ca",
"AddLine1":"Ap #416-4247 Sollicitudin Av.",
"AddLine2":"Ap #801-7380 Imperdiet Avenue",
"State":"ME",
"Country":"Israel"
},
"Marks":null,
"stdCategory":{
"Cat_ID":5,
"Category":"Normal"
}
}
我的Java类
public class Login extends AppCompatActivity implements View.OnClickListener {
EditText userName, Password;
Button login;
public static final String LOGIN_URL = "http://192.168.100.5:84/Token";
public static final String KEY_USERNAME = "UserName";
public static final String KEY_PASSWORD = "Password";
String username, password;
String accesstoken, tokentype, expiresin, masterid, name, access, issue, expires;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userName = (EditText) findViewById(R.id.login_name);
Password = (EditText) findViewById(R.id.login_password);
userName.setHint(Html.fromHtml("<font color='#008b8b' style='italic'>Username</font>"));
Password.setHint(Html.fromHtml("<font color='#008b8b'>Password</font>"));
login = (Button) findViewById(R.id.login);
login.setOnClickListener(this);
}
private void UserLogin() {
username = userName.getText().toString().trim();
password = Password.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
accesstoken = jsonObject.getString("access_token");
tokentype = jsonObject.getString("token_type");
expiresin = jsonObject.getString("expires_in");
username = jsonObject.getString("userName");
masterid = jsonObject.getString("MasterID");
//String[] parts = masterid.split("[0-9]");
//System.out.println(Arrays.toString(parts));
// parts = masterid.split("/[0-9]/g");
// parts = masterid.preg_replace('/[^0-9]/', '', $string);
name = jsonObject.getString("Name");
access = jsonObject.getString("Access");
issue = jsonObject.getString(".issued");
expires = jsonObject.getString(".expires");
SessionManagement session = new SessionManagement(Login.this);
session.createLoginSession(accesstoken, tokentype, expiresin, username, masterid, name, access, issue, expires);
// System.out.println(Arrays.toString(parts));
openProfile();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
// params.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
return params;
}
@Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
map.put(KEY_USERNAME, username);
map.put(KEY_PASSWORD, password);
map.put("grant_type", "password");
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void openProfile() {
Intent intent = new Intent(this, Home.class);
intent.putExtra(KEY_USERNAME, username);
startActivity(intent);
}
@Override
public void onClick(View v) {
UserLogin();
}
}
我们可以忽略JSON数据中使用的后缀并仅存储整数吗?
答案 0 :(得分:0)
解析JSON的最佳方法是使用Gson
。
你可以在你的gradle中将它添加到你的项目中:
compile 'com.google.code.gson:gson:2.2.+'
然后您可以轻松创建模型:
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
@SerializedName("StdID")
@Expose
private String stdID;
@SerializedName("NAME")
@Expose
private String nAME;
@SerializedName("PHONENO")
@Expose
private String pHONENO;
@SerializedName("DOB")
@Expose
private String dOB;
@SerializedName("CLASS")
@Expose
private Integer cLASS;
@SerializedName("GENDER")
@Expose
private String gENDER;
@SerializedName("ADDRESS")
@Expose
private String aDDRESS;
@SerializedName("NATIONALITY")
@Expose
private String nATIONALITY;
@SerializedName("ENROLLEDYEAR")
@Expose
private String eNROLLEDYEAR;
@SerializedName("Photo")
@Expose
private Object photo;
@SerializedName("Cat_ID")
@Expose
private Integer catID;
@SerializedName("base64")
@Expose
private Object base64;
@SerializedName("studentDetails")
@Expose
private StudentDetails studentDetails;
@SerializedName("Marks")
@Expose
private Object marks;
@SerializedName("stdCategory")
@Expose
private StdCategory stdCategory;
public String getStdID() {
return stdID;
}
public void setStdID(String stdID) {
this.stdID = stdID;
}
public String getNAME() {
return nAME;
}
public void setNAME(String nAME) {
this.nAME = nAME;
}
public String getPHONENO() {
return pHONENO;
}
public void setPHONENO(String pHONENO) {
this.pHONENO = pHONENO;
}
public String getDOB() {
return dOB;
}
public void setDOB(String dOB) {
this.dOB = dOB;
}
public Integer getCLASS() {
return cLASS;
}
public void setCLASS(Integer cLASS) {
this.cLASS = cLASS;
}
public String getGENDER() {
return gENDER;
}
public void setGENDER(String gENDER) {
this.gENDER = gENDER;
}
public String getADDRESS() {
return aDDRESS;
}
public void setADDRESS(String aDDRESS) {
this.aDDRESS = aDDRESS;
}
public String getNATIONALITY() {
return nATIONALITY;
}
public void setNATIONALITY(String nATIONALITY) {
this.nATIONALITY = nATIONALITY;
}
public String getENROLLEDYEAR() {
return eNROLLEDYEAR;
}
public void setENROLLEDYEAR(String eNROLLEDYEAR) {
this.eNROLLEDYEAR = eNROLLEDYEAR;
}
public Object getPhoto() {
return photo;
}
public void setPhoto(Object photo) {
this.photo = photo;
}
public Integer getCatID() {
return catID;
}
public void setCatID(Integer catID) {
this.catID = catID;
}
public Object getBase64() {
return base64;
}
public void setBase64(Object base64) {
this.base64 = base64;
}
public StudentDetails getStudentDetails() {
return studentDetails;
}
public void setStudentDetails(StudentDetails studentDetails) {
this.studentDetails = studentDetails;
}
public Object getMarks() {
return marks;
}
public void setMarks(Object marks) {
this.marks = marks;
}
public StdCategory getStdCategory() {
return stdCategory;
}
public void setStdCategory(StdCategory stdCategory) {
this.stdCategory = stdCategory;
}
}
-----------------------------------com.example.StdCategory.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class StdCategory {
@SerializedName("Cat_ID")
@Expose
private Integer catID;
@SerializedName("Category")
@Expose
private String category;
public Integer getCatID() {
return catID;
}
public void setCatID(Integer catID) {
this.catID = catID;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
-----------------------------------com.example.StudentDetails.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class StudentDetails {
@SerializedName("StdID")
@Expose
private Integer stdID;
@SerializedName("GUARDIAN_PHONE_NO")
@Expose
private String gUARDIANPHONENO;
@SerializedName("MOBILE_NO")
@Expose
private String mOBILENO;
@SerializedName("First_NAME")
@Expose
private String firstNAME;
@SerializedName("Last_Name")
@Expose
private String lastName;
@SerializedName("Relation")
@Expose
private String relation;
@SerializedName("DOB")
@Expose
private String dOB;
@SerializedName("Education")
@Expose
private String education;
@SerializedName("Occupation")
@Expose
private String occupation;
@SerializedName("Income")
@Expose
private String income;
@SerializedName("Email")
@Expose
private String email;
@SerializedName("AddLine1")
@Expose
private String addLine1;
@SerializedName("AddLine2")
@Expose
private String addLine2;
@SerializedName("State")
@Expose
private String state;
@SerializedName("Country")
@Expose
private String country;
public Integer getStdID() {
return stdID;
}
public void setStdID(Integer stdID) {
this.stdID = stdID;
}
public String getGUARDIANPHONENO() {
return gUARDIANPHONENO;
}
public void setGUARDIANPHONENO(String gUARDIANPHONENO) {
this.gUARDIANPHONENO = gUARDIANPHONENO;
}
public String getMOBILENO() {
return mOBILENO;
}
public void setMOBILENO(String mOBILENO) {
this.mOBILENO = mOBILENO;
}
public String getFirstNAME() {
return firstNAME;
}
public void setFirstNAME(String firstNAME) {
this.firstNAME = firstNAME;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getRelation() {
return relation;
}
public void setRelation(String relation) {
this.relation = relation;
}
public String getDOB() {
return dOB;
}
public void setDOB(String dOB) {
this.dOB = dOB;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getIncome() {
return income;
}
public void setIncome(String income) {
this.income = income;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddLine1() {
return addLine1;
}
public void setAddLine1(String addLine1) {
this.addLine1 = addLine1;
}
public String getAddLine2() {
return addLine2;
}
public void setAddLine2(String addLine2) {
this.addLine2 = addLine2;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
之后,只需使用fromJson()
方法,您就可以将任何json
转换为模型并从中检索stdId
。
更新:
如果您只想从S001
获取数字,可以这样做:
String str = "S001";
str = str.subString(1);
在此之后,您的号码在str
。