如何将gson用于json的getstring?

时间:2019-04-03 08:46:22

标签: java android json gson

我刚开始使用gson。

我在那找到了很多我可以学习gson的教程,但是这里使用了recylerview和模型文件。

JsonObjectRequest request = new JsonObjectRequest(LoginUrl, new JSONObject(params),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG , String.valueOf(response));

                        try {
                            String statusObject = response.getString("status");
                            String msgObject = response.getString("msg");

                            if (statusObject.equals("200")) {
                                JSONArray jsonArray = response.getJSONArray("response");
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject managerResponse= jsonArray.getJSONObject(i);

// userIdObject = managerResponse.getString("user_id");
// String nameObject = managerResponse.getString("name");
// String emailObject = managerResponse.getString("email");
// String mobileObject = managerResponse.getString("mobile");
// String postobject = managerResponse.getString("post");
// pojectObject = managerResponse.getString("project");
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }

在这里,我可以使用Volley从jsonrequest获取数据,但是无法使用Volley和Gson进行相同的处理。有什么方法可以使用gson吗? 谢谢。

更新

我的JSON响应

{
    "status": "200",
    "msg": "Successfully",
    "response": [
        {
            "user_id": "1",
            "name": "HEMANT OJHA",
            "email": "hemguna@gmail.com",
            "mobile": "9584919991",
            "address1": "C92, PALLAWI NAGAR BABADIYA KALAN",
            "user": "admin",
            "api_token": "admin"
        }
    ]
}

3 个答案:

答案 0 :(得分:0)

尝试一下

JSON response

String str = new Gson().toJson(response) 

答案 1 :(得分:0)

Generating POJO class from JSON

// Considering your response consists of json objects & json array
// Create a POJO class for your response with the link above

{
"keyOne": 1,
"keyTwo": "Some Value",
"someArray": [{
        "key": "Value"
    },
    {
        "key": "Value"
    }
]
}



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

 public class ExampleClass {

   @SerializedName("keyOne")
   @Expose
   private int keyOne;
   @SerializedName("keyTwo")
   @Expose
   private String keyTwo;
   @SerializedName("someArray")
   @Expose
   private List<SomeArray> someArray = null;

   public int getKeyOne() {
   return keyOne;
   }

   public void setKeyOne(int keyOne) {
   this.keyOne = keyOne;
   }

   public String getKeyTwo() {
   return keyTwo;
   }

   public void setKeyTwo(String keyTwo) {
   this.keyTwo = keyTwo;
   }

   public List<SomeArray> getSomeArray() {
   return someArray;
   }

  public void setSomeArray(List<SomeArray> someArray) {
  this.someArray = someArray;
   }

  }

  // Parsing JSON response with GSON
  GsonBuilder gsonBuilder = new GsonBuilder();
  Gson gson = gsonBuilder.create();
  ExampleClass resultObj = gson.fromJson(jsonObject.toString(), ExampleClass.class);
  int keyOneValue = resultObj.getKeyOne() // First JSON Object 
  // Getting String value
  String keyTwoValue = resultObj.getKeyTwo() // Second JSON Object 
  List<SomeArray> yourJSONArray = resultObj.getSomeArray() // Getting JSON Array contents

//取决于您在问题中更新的JSON响应

 GsonBuilder gsonBuilder = new GsonBuilder();
 Gson gson = gsonBuilder.create();
 ExampleClass resultObj = gson.fromJson(jsonObject.toString(),ExampleClass.class);
 String status = resultObj.getStatus();
 String msg = resultObj.getMsg();
 List<Response> responseList = resultObj.getResponse();

答案 2 :(得分:0)

使用整个应用程序的最佳方法是创建一个Utils类,并将其用于转换。

GsonUtils.java

//  This Class is useful for mapping Json into Java Objects and vice versa.
public class GsonUtils {

    private static final Gson gson = new Gson();

    //  This will Convert Java Objects into JSON String...
    public static String toGson(Object object) {
        return gson.toJson(object);
    }

    //  Gives Java Objects from JSON
    public static <T> T fromGson(String json, Class<T> type) {
        return gson.fromJson(json, type);
    }

    public static JsonArray fromGson(String json) {
        return new JsonParser().parse(json).getAsJsonArray();
    }
}

现在可以通过以下方式将任意json与POJO相互转换

POJO pojoObj = GsonUtils.toGson(POJO.class);