2017-03-16 45 views
-3

我想從服務器轉換爲JSON字符串的響應,我想將該JSONstring轉換爲java object.I正在嘗試Gson.Please有人解釋並告訴我如何使用Gson做到這一點。我如何將json字符串轉換爲android中的java對象?

@Override 
     public void onClick(View v) { 
      if (v == mLoginButton) { 
       LoginUser(); 

      } 
      if (v==mSignUpBtn){ 
       Intent intent=new Intent(LoginActivity.this,RegistrationActivity.class); 
       startActivity(intent); 
      } 
     } 

     private void LoginUser() { 
      // final String username = editTextUsername.getText().toString().trim(); 
      final String password = editTextPassword.getText().toString().trim(); 
      final String email = editTextEmail.getText().toString().trim(); 



      StringRequest postStringRequest = new StringRequest(Request.Method.POST,LOGIN_API, 
        new Response.Listener<String>() { 
         @Override 
         public void onResponse(String response) { 
          Toast.makeText(LoginActivity.this, response, Toast.LENGTH_LONG).show(); 
          Log.d(TAG,"Reponse Check :"+response); 
          // Gson gson = new Gson(); 
          // String jsonInString = "{}"; 
          //LoginActivity staff = gson.fromJson(jsonInString, LoginActivity.class); 
          //Log.d(TAG,"Reponse Check staff :"+staff); 

         } 
        }, 
        new Response.ErrorListener() { 
         @Override 
         public void onErrorResponse(VolleyError error) { 
          Toast.makeText(LoginActivity.this, error.toString(), Toast.LENGTH_LONG).show(); 
          Log.e(TAG,"Error Response Check :"+error); 
         } 
        }) { 

       @Override 
       protected Map<String, String> getParams() { 
        Map<String, String> params = new HashMap<String, String>(); 

        Log.d(TAG,"For email :"+email); 
        Log.d(TAG,"For password :"+password); 
        //try { 
         Log.d(TAG,"My Credentials email URL Encoder: "+(mEncryption.AESEncode(email))); 
         Log.d(TAG,"My Credentials email URL DECODED: "+(mEncryption.AESDecode(mEncryption.AESEncode(email)))); 

         params.put("data[User][email]",(mEncryption.AESEncode(email))); 

         Log.d(TAG,"My Credentials pass URL Encoder: "+(mEncryption.AESEncode(password))); 
         paa 
       } 

logcat的

03-16 16:36:08.346 2618-3428/com.example.user.myapplication D/Null: For email :[email protected] 
03-16 16:36:08.346 2618-3428/com.example.user.myapplication D/Null: For password :12345678 
03-16 16:36:08.354 2618-3428/com.example.user.myapplication D/Null: My Credentials email URL Encoder: RyUMRBg7UyeIlFBBtNemZFuG46PJtAIdiZWXnlJ4zNI= 
03-16 16:36:08.358 2618-3428/com.example.user.myapplication D/Null: My Credentials email URL DECODED: [email protected] 
03-16 16:36:08.360 2618-3428/com.example.user.myapplication D/Null: My Credentials pass URL Encoder: pfrt1fKLkoZhAT6hoMJFiA== 
03-16 16:36:08.361 2618-3428/com.example.user.myapplication D/Null: Params :{data[User][password]=pfrt1fKLkoZhAT6hoMJFiA== 
                    , data[User][email]=RyUMRBg7UyeIlFBBtNemZFuG46PJtAIdiZWXnlJ4zNI= 
                    } 
03-16 16:36:08.505 2618-2618/com.example.user.myapplication D/Null: Reponse Check :{"code":200,"user":{"User":{"id":"ui1bJkK19jxbaquTboA2oQ==","email":"RyUMRBg7UyeIlFBBtNemZFuG46PJtAIdiZWXnlJ4zNI=","status":"1","verified":"1","created":"2016-03-07 11:41:59","modified":"2016-04-07 15:43:43","token":"6b987332b77d7c69d76bf7be80a85177fb7fa08d"},"Profile":{"id":"1","first_name":"abc","last_name":"fgh","bio":"sfafaf","address":"82, Debinibash Road\r\nDum Dum, P.O. - Motijheel","phone":"+913325505055","profile_pic":"\/img\/356a192b7913b04c54574d18c28d46e6395428ab\/license.jpg","user_id":"1","Contributor":{"id":"31","profile_id":"1","status":"1","vs_cdn_id":"261961777","secret_token":"s-7Va5z","uploaded_on":null,"statement":"AOK KJDHKJDH bkgkg kkhkjh kjhkj kjh kjhkjh","time":"7 hours per month","created":"2016-05-02 18:40:11","modified":"2016-05-02 18:41:29"},"Moderator":[]},"redirect":"\/"}} 
+0

你可以在這裏找到一個關於Gson的好教程http://howtodoinjava.com/best-practices/google-gson-tutorial-convert-java- object-to-from-json/ –

+0

https://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/ –

回答

0

您可以在一個通用的方式使用,如:

private final static Gson GSON = new GsonBuilder().create(); 

public static <T> T fromJSON(String json, Class<T> clazz) { 
    try { 
     return GSON.fromJson(json, clazz); 
    } catch (JsonSyntaxException e) { 
     LOGGER.warn("Could not deserialize object", e); 
    } 
    return null; 
} 
0

您不能從JSON使活動/片段。

在你onResponse()方法:

ModelObject obj = new Gson().fromJson(jsonString, ModelObject.class); 

而且使ModelObject類是這樣的:

public class ModelObject { 
int field1; 
int field2; 
//here you should make getters and setters; 
} 

它後,你可以做任何你需要使用這個對象(它傳遞到任何活動或片段)。

+0

你能否給予更多提示在ModelObject類上,也關於ge tter二傳手。 – user7328722

+0

你已經創建了模型類(User_)和getter和setter(查看以get ***和set ***開頭的方法),現在只需用User替換ModelObject – Arthur

0

如果字段是正確給定的,Gson會將值映射到相應的模型類對象。看看下面的模型類。之後,如果你打電話給Example data = GSON.fromJson(yourJson, Example.class);,這個數據對象將擁有你所需要的一切。

----------------------------------- com.example.Contributor.java ---- -------------------------------

package com.example; 

import com.google.gson.annotations.Expose; 
import com.google.gson.annotations.SerializedName; 

public class Contributor { 

@SerializedName("id") 
@Expose 
private String id; 
@SerializedName("profile_id") 
@Expose 
private String profileId; 
@SerializedName("status") 
@Expose 
private String status; 
@SerializedName("vs_cdn_id") 
@Expose 
private String vsCdnId; 
@SerializedName("secret_token") 
@Expose 
private String secretToken; 
@SerializedName("uploaded_on") 
@Expose 
private Object uploadedOn; 
@SerializedName("statement") 
@Expose 
private String statement; 
@SerializedName("time") 
@Expose 
private String time; 
@SerializedName("created") 
@Expose 
private String created; 
@SerializedName("modified") 
@Expose 
private String modified; 

public String getId() { 
return id; 
} 

public void setId(String id) { 
this.id = id; 
} 

public String getProfileId() { 
return profileId; 
} 

public void setProfileId(String profileId) { 
this.profileId = profileId; 
} 

public String getStatus() { 
return status; 
} 

public void setStatus(String status) { 
this.status = status; 
} 

public String getVsCdnId() { 
return vsCdnId; 
} 

public void setVsCdnId(String vsCdnId) { 
this.vsCdnId = vsCdnId; 
} 

public String getSecretToken() { 
return secretToken; 
} 

public void setSecretToken(String secretToken) { 
this.secretToken = secretToken; 
} 

public Object getUploadedOn() { 
return uploadedOn; 
} 

public void setUploadedOn(Object uploadedOn) { 
this.uploadedOn = uploadedOn; 
} 

public String getStatement() { 
return statement; 
} 

public void setStatement(String statement) { 
this.statement = statement; 
} 

public String getTime() { 
return time; 
} 

public void setTime(String time) { 
this.time = time; 
} 

public String getCreated() { 
return created; 
} 

public void setCreated(String created) { 
this.created = created; 
} 

public String getModified() { 
return modified; 
} 

public void setModified(String modified) { 
this.modified = modified; 
} 

} 

------------ ----------------------- com.example.Example.java -------------------- ---------------

package com.example; 

import com.google.gson.annotations.Expose; 
import com.google.gson.annotations.SerializedName; 

public class Example { 

@SerializedName("code") 
@Expose 
private Integer code; 
@SerializedName("user") 
@Expose 
private User user; 

public Integer getCode() { 
return code; 
} 

public void setCode(Integer code) { 
this.code = code; 
} 

public User getUser() { 
return user; 
} 

public void setUser(User user) { 
this.user = user; 
} 

} 

---------------------------- ------- com.example.Profile.java -----------------------------------

package com.example; 

import java.util.List; 
import com.google.gson.annotations.Expose; 
import com.google.gson.annotations.SerializedName; 

public class Profile { 

@SerializedName("id") 
@Expose 
private String id; 
@SerializedName("first_name") 
@Expose 
private String firstName; 
@SerializedName("last_name") 
@Expose 
private String lastName; 
@SerializedName("bio") 
@Expose 
private String bio; 
@SerializedName("address") 
@Expose 
private String address; 
@SerializedName("phone") 
@Expose 
private String phone; 
@SerializedName("profile_pic") 
@Expose 
private String profilePic; 
@SerializedName("user_id") 
@Expose 
private String userId; 
@SerializedName("Contributor") 
@Expose 
private Contributor contributor; 
@SerializedName("Moderator") 
@Expose 
private List<Object> moderator = null; 

public String getId() { 
return id; 
} 

public void setId(String id) { 
this.id = id; 
} 

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 getBio() { 
return bio; 
} 

public void setBio(String bio) { 
this.bio = bio; 
} 

public String getAddress() { 
return address; 
} 

public void setAddress(String address) { 
this.address = address; 
} 

public String getPhone() { 
return phone; 
} 

public void setPhone(String phone) { 
this.phone = phone; 
} 

public String getProfilePic() { 
return profilePic; 
} 

public void setProfilePic(String profilePic) { 
this.profilePic = profilePic; 
} 

public String getUserId() { 
return userId; 
} 

public void setUserId(String userId) { 
this.userId = userId; 
} 

public Contributor getContributor() { 
return contributor; 
} 

public void setContributor(Contributor contributor) { 
this.contributor = contributor; 
} 

public List<Object> getModerator() { 
return moderator; 
} 

public void setModerator(List<Object> moderator) { 
this.moderator = moderator; 
} 

} 

----------------------------------- com.example.User.java ------ -----------------------------

package com.example; 

import com.google.gson.annotations.Expose; 
import com.google.gson.annotations.SerializedName; 

public class User { 

@SerializedName("User") 
@Expose 
private User_ user; 
@SerializedName("Profile") 
@Expose 
private Profile profile; 
@SerializedName("redirect") 
@Expose 
private String redirect; 

public User_ getUser() { 
return user; 
} 

public void setUser(User_ user) { 
this.user = user; 
} 

public Profile getProfile() { 
return profile; 
} 

public void setProfile(Profile profile) { 
this.profile = profile; 
} 

public String getRedirect() { 
return redirect; 
} 

public void setRedirect(String redirect) { 
this.redirect = redirect; 
} 

} 

-------------- --------------------- com.example.User_.java ---------------------- -------------

package com.example; 

import com.google.gson.annotations.Expose; 
import com.google.gson.annotations.SerializedName; 

public class User_ { 

@SerializedName("id") 
@Expose 
private String id; 
@SerializedName("email") 
@Expose 
private String email; 
@SerializedName("status") 
@Expose 
private String status; 
@SerializedName("verified") 
@Expose 
private String verified; 
@SerializedName("created") 
@Expose 
private String created; 
@SerializedName("modified") 
@Expose 
private String modified; 
@SerializedName("token") 
@Expose 
private String token; 

public String getId() { 
return id; 
} 

public void setId(String id) { 
this.id = id; 
} 

public String getEmail() { 
return email; 
} 

public void setEmail(String email) { 
this.email = email; 
} 

public String getStatus() { 
return status; 
} 

public void setStatus(String status) { 
this.status = status; 
} 

public String getVerified() { 
return verified; 
} 

public void setVerified(String verified) { 
this.verified = verified; 
} 

public String getCreated() { 
return created; 
} 

public void setCreated(String created) { 
this.created = created; 
} 

public String getModified() { 
return modified; 
} 

public void setModified(String modified) { 
this.modified = modified; 
} 

public String getToken() { 
return token; 
} 

public void setToken(String token) { 
this.token = token; 
} 

} 
相關問題