我有一个json,我需要一些格式帮助,以便我可以将值保存在SharedPreferences中,这是困扰我的代码。
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.cumaskp.mercfood";
private SharedPreferences mPreferences;
private SharedPreferences.Editor mEditor;
EditText username;
EditText password;
Button loginbutton;
Button signupBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mEditor = mPreferences.edit();
username = (EditText) findViewById(R.id.usernameEditText);
password = (EditText) findViewById(R.id.mailEditText);
signupBtn = (Button) findViewById(R.id.signUpButton);
loginbutton = (Button) findViewById(R.id.loginBtn);
signupBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view){
Intent myIntent = new Intent(MainActivity.this, getData.class);
MainActivity.this.startActivity(myIntent);
}
});
loginbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new SendPostRequest().execute();
}
});
}
public class SendPostRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try {
URL url = new URL("http://192.168.111.42/api/login"); //TODO here is your URL path
JSONObject postDataParams = new JSONObject();
postDataParams.put("username", username.getText().toString());
postDataParams.put("password", password.getText().toString());
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
@Override
protected void onPostExecute(String result) {
// it is right here the problem is! -----------------------------------------------------------------------------
try {
for (int i = 0; i < result.length(); i++) {
JSONObject jsonObj = result.getJSONObject(i);
String k = jsonObj.keys().next();
Log.i("Info", "Key: " + k + ", value: " + jsonObj.getString(k));
}
} catch (JSONException ex) {
ex.printStackTrace();
}
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
mEditor.putString("token",result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
String token = mPreferences.getString("key", "default");
Log.d("myTag", "onPostExecute: "+ token);
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
我认为这个问题经常被问到,但是我尝试用谷歌搜索一个答案,目前还不清楚我应该如何将字符串格式化为变量。
我的应用中的字符串输出看起来像这样:{"api_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJsdW1lbi1qd3QiLCJzdWIiOjEsImlhdCI6MTU0MTQyNjYxMiwiZXhwIjoxNTQxNTEzMDEyLCJuYW0iOiIxMjM0In0.7TR1ueOB-xqAkI6XgStUnn7HZxBTvxx3wzjKGHDnD4I","user_id":1}
有人告诉我,代码越多越好,所有内容中间都有一个指针。
答案 0 :(得分:1)
这看起来非常复杂,假设json String是您要取回的格式,您所要做的就是将其输入JSON对象:
JSONObject obj = new JSONObject(responseString);
然后您可以直接访问数据:
String token = obj.getString("api_token");
int userID = obj.getInt("user_id");
然后,您可以对他们进行任何操作。
答案 1 :(得分:1)
您不需要创建变量。
由于响应是字符串,
保存json本身,
我也看到语法错误OnPostExecute()
,result
参数是string,string没有名为getJsonObject()
的方法,因此您需要执行以下操作
JSONObject resultAsJsonObject=new JSONObject(result);
以上方法可以让您将变量用作与字符串不同的对象
我建议您将整个json保存到共享首选项中,因此您此时无需进行转换 您可以创建模型并使用GSON,以便您无需将其转换为JSONObject,但是结果将为json结构,Gson库会将您的json结果转换为Java对象