仅选择“选定的JSON值"并保存在sharedPreferences中? [英] Choose only Selected JSON Value and save in sharedPreferences?

查看:114
本文介绍了仅选择“选定的JSON值"并保存在sharedPreferences中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够解析JSON数据.究竟是什么问题,我想将学生ID存储在SharedPreference中而没有后缀,即仅存储整数?我曾尝试用REGEX分割JSON值,但由于我没有使用过regex,所以无法分割.如何解决此问题?

I am Able to Parse JSON Data.Exactly what is the issue is that ,i want to store the Student ID in the SharedPreference without suffix i.e means only the integer is to be stored? I have tried to split the JSON Value with REGEX but not able,since i have not used regex.How can this issue be solved??

{

    "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数据中使用的后缀而只存储整数吗?

can we neglect suffix used in JSON Data and store only integer?

推荐答案

解析JSON的最佳方法是使用Gson. 您可以将其添加到您的gradle中的项目中:

The best way to pars a JSON is by using Gson. U can add it to your project in your gradle:

compile 'com.google.code.gson:gson:2.2.+'

然后,您可以轻松创建模型:

Then you can easily create your model:

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

After that, just with fromJson() method, you can convert any json to your model and retrieve your stdId from it.

更新:

如果您只想从S001中获取电话号码,则可以通过以下方式进行操作:

If you want to get only the number from S001 you can do it this way:

String str = "S001";
str = str.subString(1);

在此之后,您的电话号码在str中.

after this, you have your number in str.

这篇关于仅选择“选定的JSON值"并保存在sharedPreferences中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆