Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/215.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 仅选择选定的JSON值并保存在SharedReferences中?_Android_Json_Regex_Sharedpreferences - Fatal编程技术网

Android 仅选择选定的JSON值并保存在SharedReferences中?

Android 仅选择选定的JSON值并保存在SharedReferences中?,android,json,regex,sharedpreferences,Android,Json,Regex,Sharedpreferences,我能够解析JSON数据。问题是,我想在SharedReference中存储学生ID,不带后缀,即只存储整数?我曾尝试用正则表达式分割JSON值,但无法,因为我没有使用正则表达式。如何解决这个问题 { "StdID":S001, "NAME":"Kirsten Green", "PHONENO":"095-517-0049", "DOB":"2009-12-28T00:00:00", "CLASS":9, "GENDER":"M", "AD

我能够解析JSON数据。问题是,我想在SharedReference中存储学生ID,不带后缀,即只存储整数?我曾尝试用正则表达式分割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();
    }


}
公共类登录扩展AppCompatActivity实现View.OnClickListener{
编辑文本用户名、密码;
按钮登录;
公共静态最终字符串登录\u URL=”http://192.168.100.5:84/Token";
公共静态最终字符串键\u USERNAME=“USERNAME”;
公共静态最终字符串密钥\u PASSWORD=“PASSWORD”;
字符串用户名、密码;
字符串accesstoken、tokentype、expiresin、masterid、名称、访问、发布、过期;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u登录);
用户名=(EditText)findViewById(R.id.login\u name);
密码=(EditText)findViewById(R.id.login\u密码);
userName.setHint(Html.fromHtml(“用户名”));
Password.setHint(Html.fromHtml(“密码”));
login=(按钮)findviewbyd(R.id.login);
login.setOnClickListener(this);
}
私有void UserLogin(){
username=username.getText().toString().trim();
password=password.getText().toString().trim();
StringRequest StringRequest=新的StringRequest(Request.Method.POST、LOGIN\u URL、,
新的Response.Listener(){
@凌驾
公共void onResponse(字符串响应){
试一试{
JSONObject JSONObject=新JSONObject(响应);
accesstoken=jsonObject.getString(“访问令牌”);
tokentype=jsonObject.getString(“token_type”);
expiresin=jsonObject.getString(“expires_in”);
username=jsonObject.getString(“用户名”);
masterid=jsonObject.getString(“masterid”);
//字符串[]parts=masterid.split(“[0-9]”);
//System.out.println(Arrays.toString(parts));
//零件=主ID分割(“/[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=新的SessionManagement(Login.this);
createLoginSession(accesstoken、tokentype、expiresin、用户名、masterid、名称、访问、发布、过期);
//System.out.println(Arrays.toString(parts));
openProfile();
}捕获(JSONException e){
Toast.makeText(getApplicationContext(),“获取失败!”,Toast.LENGTH\u SHORT.show();
e、 printStackTrace();
}
}
},
新的Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Toast.makeText(Login.this,error.toString(),Toast.LENGTH_LONG).show();
}
}) {
@凌驾
公共映射getHeaders()引发AuthFailureError{
Map params=新的HashMap();
//参数put(“内容类型”,“应用程序/x-www-form-urlencoded;字符集=utf-8”);
返回参数;
}
@凌驾
受保护的映射getParams(){
Map Map=newhashmap();
map.put(KEY_用户名,USERNAME);
map.put(KEY_密码,PASSWORD);
map.put(“授权类型”、“密码”);
返回图;
}
};
stringRequest.setRetryPolicy(新的DefaultRetryPolicy(
60000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue RequestQueue=Volley.newRequestQueue(this);
添加(stringRequest);
}
私有void openProfile(){
意向意向=新意向(此,Home.class);
intent.putExtra(KEY_用户名、用户名);
星触觉(意向);
}
@凌驾
公共void onClick(视图v){
UserLogin();
}
}
我们可以忽略JSON数据中使用的后缀而只存储整数吗


解析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

中有了你的数字,因为JSON数据由S001组成。但是我只需要存储001,忽略S。这是怎么可能的?你的问题实际上是如何删除字符串的第一个字符?@seon是的,你的问题完全是另一回事@david.mihola是的,david,这个问题怎么解决呢?添加这行masterid=masterid.replaceAll(“[^\\\.0123456789]”,“);我只能选择整数