如何正确阅读以下JSON以存储在Model
中{
"data": {
"success": "true",
"orders": [
{
"orderId": "5",
"prefix": "OID-MKFQ7-00000",
"status": "C",
"createdOn": "2018-03-30 16:21:59",
"createdBy": "1016",
"tax": "21.20",
"shippingCharges": "0.00",
"deliveryCode": "",
"shopId": "3",
"amount": "291.2",
"subTotal": "270",
"discount": "0",
"couponCode": "",
"productDetails": [
{
"productId": "44",
"storeId": "3",
"productName": "Tata Sampann Toor Dal ",
"quantity": "5",
"productAmount": "54.00",
"totalAmount": 270,
"optionDetails": {
"optionId": "49",
"optionName": "Available in (Units):500 gm",
"optionAmount": "54"
}
}
],
"userAddressDetails": {
"firstName": "",
"middleName": "",
"lastName": "",
"email": "9284314578@mailinator.com",
"mobileNo": "9284314578",
"address": "Savali Society Rd",
"landMark": "Industrial Estate",
"city": "Ichalkaranji",
"zipCode": "416117",
"stateName": "Maharashtra",
"countryName": "India",
"latitude": "16.719247500000016",
"longitude": "74.45389453124999"
}
},
{
"orderId": "6",
"prefix": "OID-G4KHX-00000",
"status": "C",
"createdOn": "2018-04-10 17:45:22",
"createdBy": "1011",
"tax": "42.41",
"shippingCharges": "0.00",
"deliveryCode": "",
"shopId": "3",
"amount": "582.41",
"subTotal": "540",
"discount": "0",
"couponCode": "",
"productDetails": [
{
"productId": "44",
"storeId": "3",
"productName": "Tata Sampann Toor Dal ",
"quantity": "10",
"productAmount": "54.00",
"totalAmount": 540,
"optionDetails": {
"optionId": "49",
"optionName": "Available in (Units):500 gm",
"optionAmount": "54"
}
}
],
"userAddressDetails": {
"firstName": "test",
"middleName": "",
"lastName": "test",
"email": "test@test.com",
"mobileNo": "8446363349",
"address": "New Shahupuri, 204, Kolhapur Station Rd",
"landMark": "Tarabai Park",
"city": "Kolhapur",
"zipCode": "416001",
"stateName": "Maharashtra",
"countryName": "India",
"latitude": "16.704987299999996",
"longitude": "74.24325270000001"
}
}
]
}
}
我试过
{
final JSONObject output = response.getJSONObject("data");
if (output.getString("success").equalsIgnoreCase("true")) {
final JSONArray orderDetails = output.getJSONArray("orders");
for (int i = 0; i < orderDetails.length(); i++) {
// Get single order object
JSONObject orderData = orderDetails.getJSONObject(i);
// Get product details object
JSONArray products = orderData.getJSONArray("productDetails");
for (int k = 0; k < products.length(); k++) {
JSONObject productData = products.getJSONObject(k);
JSONObject optionData = productData.getJSONObject("optionDetails");
ProductDetailsModel product = new ProductDetailsModel(
productData.getString("productId"),
productData.getString("storeId"),
productData.getString("productName"),
productData.getString("quantity"),
productData.getString("productAmount"),
productData.getString("totalAmount"),
optionData.getString("optionId"),
optionData.getString("optionName"),
optionData.getString("optionAmount")
);
productsList.add(product);
//System.out.println(productsList);
for (int j =0; j< productsList.size(); j++){
System.out.println("Hey data: "+productsList.get(j).getQuantity());
}
}
// Get user address object
JSONObject userAddress = orderData.getJSONObject("userAddressDetails");
UserAddressDetailsModel addressModel = new UserAddressDetailsModel(
userAddress.getString("firstName"), userAddress.getString("middleName"),
userAddress.getString("lastName"), userAddress.getString("email"),
userAddress.getString("mobileNo"), userAddress.getString("address"),
userAddress.getString("landMark"), userAddress.getString("city"),
userAddress.getString("zipCode"), userAddress.getString("stateName"),
userAddress.getString("countryName"), userAddress.getString("latitude"),
userAddress.getString("longitude"));
ordersList.add(addressModel);
Order order = new Order(orderData.getString("tax"),
orderData.getString("shippingCharges"),
orderData.getString("amount"),
orderData.getString("subTotal"),
orderData.getString("discount"),
orderData.getString("prefix"),
orderData.getString("createdOn"),
orderData.getString("couponCode"),
orderData.getString("orderId"),
orderData.getString("deliveryCode"),
orderData.getString("shopId"),
orderData.getString("createdBy"),
orderData.getString("status"),
productsList, addressModel);
orders.add(order);
}
adapter.notifyDataSetChanged();
} else{
Toast.makeText(getActivity(), output.getString("message"), Toast.LENGTH_LONG).show();
}
}
它导致子( productDetails )嵌套父(订单)json数组的json数组中的重复条目。
答案 0 :(得分:1)
试试这个
try {
JSONObject jsonObject= new JSONObject(readJSONFromAsset());
JSONObject mainJsonObject = jsonObject.getJSONObject("data");
String success = mainJsonObject.getString("success");
JSONArray orders = mainJsonObject.getJSONArray("orders");
for (int i = 0; i < orders.length(); i++) {
JSONObject orderJsonObject = orders.getJSONObject(i);
String orderId=orderJsonObject.getString("orderId");
String prefix=orderJsonObject.getString("prefix");
String status=orderJsonObject.getString("status");
String createdOn=orderJsonObject.getString("createdOn");
String createdBy=orderJsonObject.getString("createdBy");
String tax=orderJsonObject.getString("tax");
String shippingCharges=orderJsonObject.getString("shippingCharges");
String deliveryCode=orderJsonObject.getString("deliveryCode");
String shopId=orderJsonObject.getString("shopId");
String amount=orderJsonObject.getString("amount");
String subTotal=orderJsonObject.getString("subTotal");
String discount=orderJsonObject.getString("discount");
String couponCode=orderJsonObject.getString("couponCode");
JSONArray productDetails=orderJsonObject.getJSONArray("productDetails");
for (int j=0;j<productDetails.length();j++){
JSONObject productDeatilObject=productDetails.getJSONObject(j);
String productId=productDeatilObject.getString("productId");
String storeId=productDeatilObject.getString("storeId");
String productName=productDeatilObject.getString("productName");
String quantity=productDeatilObject.getString("quantity");
String productAmount=productDeatilObject.getString("productAmount");
String totalAmount=productDeatilObject.getString("totalAmount");
JSONObject optionDetails=productDeatilObject.getJSONObject("optionDetails");
String optionId=optionDetails.getString("optionId");
String optionName=optionDetails.getString("optionName");
String optionAmount=optionDetails.getString("optionAmount");
}
JSONObject userAddressDetails=orderJsonObject.getJSONObject("userAddressDetails");
String firstName=userAddressDetails.getString("firstName");
String middleName=userAddressDetails.getString("middleName");
String lastName=userAddressDetails.getString("lastName");
String email=userAddressDetails.getString("email");
String mobileNo=userAddressDetails.getString("mobileNo");
String address=userAddressDetails.getString("address");
String landMark=userAddressDetails.getString("landMark");
String city=userAddressDetails.getString("city");
String zipCode=userAddressDetails.getString("zipCode");
String stateName=userAddressDetails.getString("stateName");
String countryName=userAddressDetails.getString("countryName");
String latitude=userAddressDetails.getString("latitude");
String longitude=userAddressDetails.getString("longitude");
}
} catch (JSONException e) {
e.printStackTrace();
}
修改强>
您可以使用Gson
来解析JSON
Gson
是一个Java库,可用于将Java对象转换为JSON
表示形式。它还可用于将JSON
字符串转换为等效的Java对象。Gson
可以处理任意Java对象,包括您没有源代码的预先存在的对象。
使用http://www.jsonschema2pojo.org/
创建pojo类您的回复的示例POJO CLASS
数据类
public class Data {
@SerializedName("success")
@Expose
private String success;
@SerializedName("orders")
@Expose
private List<Order> orders = null;
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public List<Order> getOrders() {
return orders;
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
}
示例类
public class Example {
@SerializedName("data")
@Expose
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
OptionDetails类
public class OptionDetails {
@SerializedName("optionId")
@Expose
private String optionId;
@SerializedName("optionName")
@Expose
private String optionName;
@SerializedName("optionAmount")
@Expose
private String optionAmount;
public String getOptionId() {
return optionId;
}
public void setOptionId(String optionId) {
this.optionId = optionId;
}
public String getOptionName() {
return optionName;
}
public void setOptionName(String optionName) {
this.optionName = optionName;
}
public String getOptionAmount() {
return optionAmount;
}
public void setOptionAmount(String optionAmount) {
this.optionAmount = optionAmount;
}
}
订单类
public class Order {
@SerializedName("orderId")
@Expose
private String orderId;
@SerializedName("prefix")
@Expose
private String prefix;
@SerializedName("status")
@Expose
private String status;
@SerializedName("createdOn")
@Expose
private String createdOn;
@SerializedName("createdBy")
@Expose
private String createdBy;
@SerializedName("tax")
@Expose
private String tax;
@SerializedName("shippingCharges")
@Expose
private String shippingCharges;
@SerializedName("deliveryCode")
@Expose
private String deliveryCode;
@SerializedName("shopId")
@Expose
private String shopId;
@SerializedName("amount")
@Expose
private String amount;
@SerializedName("subTotal")
@Expose
private String subTotal;
@SerializedName("discount")
@Expose
private String discount;
@SerializedName("couponCode")
@Expose
private String couponCode;
@SerializedName("productDetails")
@Expose
private List<ProductDetail> productDetails = null;
@SerializedName("userAddressDetails")
@Expose
private UserAddressDetails userAddressDetails;
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCreatedOn() {
return createdOn;
}
public void setCreatedOn(String createdOn) {
this.createdOn = createdOn;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getTax() {
return tax;
}
public void setTax(String tax) {
this.tax = tax;
}
public String getShippingCharges() {
return shippingCharges;
}
public void setShippingCharges(String shippingCharges) {
this.shippingCharges = shippingCharges;
}
public String getDeliveryCode() {
return deliveryCode;
}
public void setDeliveryCode(String deliveryCode) {
this.deliveryCode = deliveryCode;
}
public String getShopId() {
return shopId;
}
public void setShopId(String shopId) {
this.shopId = shopId;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getSubTotal() {
return subTotal;
}
public void setSubTotal(String subTotal) {
this.subTotal = subTotal;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public String getCouponCode() {
return couponCode;
}
public void setCouponCode(String couponCode) {
this.couponCode = couponCode;
}
public List<ProductDetail> getProductDetails() {
return productDetails;
}
public void setProductDetails(List<ProductDetail> productDetails) {
this.productDetails = productDetails;
}
public UserAddressDetails getUserAddressDetails() {
return userAddressDetails;
}
public void setUserAddressDetails(UserAddressDetails userAddressDetails) {
this.userAddressDetails = userAddressDetails;
}
}
ProductDetail class
public class ProductDetail {
@SerializedName("productId")
@Expose
private String productId;
@SerializedName("storeId")
@Expose
private String storeId;
@SerializedName("productName")
@Expose
private String productName;
@SerializedName("quantity")
@Expose
private String quantity;
@SerializedName("productAmount")
@Expose
private String productAmount;
@SerializedName("totalAmount")
@Expose
private Integer totalAmount;
@SerializedName("optionDetails")
@Expose
private OptionDetails optionDetails;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getStoreId() {
return storeId;
}
public void setStoreId(String storeId) {
this.storeId = storeId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getProductAmount() {
return productAmount;
}
public void setProductAmount(String productAmount) {
this.productAmount = productAmount;
}
public Integer getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(Integer totalAmount) {
this.totalAmount = totalAmount;
}
public OptionDetails getOptionDetails() {
return optionDetails;
}
public void setOptionDetails(OptionDetails optionDetails) {
this.optionDetails = optionDetails;
}
}
UserAddressDetails类
public class UserAddressDetails {
@SerializedName("firstName")
@Expose
private String firstName;
@SerializedName("middleName")
@Expose
private String middleName;
@SerializedName("lastName")
@Expose
private String lastName;
@SerializedName("email")
@Expose
private String email;
@SerializedName("mobileNo")
@Expose
private String mobileNo;
@SerializedName("address")
@Expose
private String address;
@SerializedName("landMark")
@Expose
private String landMark;
@SerializedName("city")
@Expose
private String city;
@SerializedName("zipCode")
@Expose
private String zipCode;
@SerializedName("stateName")
@Expose
private String stateName;
@SerializedName("countryName")
@Expose
private String countryName;
@SerializedName("latitude")
@Expose
private String latitude;
@SerializedName("longitude")
@Expose
private String longitude;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getLandMark() {
return landMark;
}
public void setLandMark(String landMark) {
this.landMark = landMark;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
使用
Gson
解析,如下面的代码
String apiResponse = readJSONFromAsset();
Gson gson = new GsonBuilder().create();
Example resultObj = gson.fromJson(apiResponse, Example.class);
ArrayList<Order> orders = new ArrayList<>();
orders.addAll(resultObj.getData().getOrders());
Log.e("_SIZE", orders.size()+"_SIZE");
for (int i = 0; i < orders.size(); i++) {
Log.e("resultOb", orders.get(i).getAmount()+"amount");
Log.e("resultOb", orders.get(i).getCouponCode()+"getCouponCode");
Log.e("resultOb", orders.get(i).getDeliveryCode()+"getDeliveryCode");
for (int j=0;j<orders.get(i).getProductDetails().size();j++){
Log.e("resultOb", orders.get(i).getProductDetails().get(j).getTotalAmount() + "");
Log.e("resultOb", orders.get(i).getProductDetails().get(j).getProductId() + "");
Log.e("resultOb", orders.get(i).getProductDetails().get(j).getProductName() + "");
Log.e("resultOb", orders.get(i).getProductDetails().get(j).getQuantity() + "");
}
}
答案 1 :(得分:1)
这样做。我做了这个,它正在无缝地工作。
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.mocky.io/v2/5affc3ae310000970076de82";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
// Log.e("response",response);
try {
JSONObject res = new JSONObject(response);
JSONObject data= res.getJSONObject("data");
String success=data.getString("success");
if (success.equalsIgnoreCase("true")){
JSONArray array=data.getJSONArray("orders");
for (int i=0;i<array.length();i++){
JSONObject jsonObject=array.getJSONObject(i);
String orderid=jsonObject.getString("orderId");
String prefix=jsonObject.getString("prefix");
String status=jsonObject.getString("status");
String createdOn=jsonObject.getString("createdOn");
String tax=jsonObject.getString("tax");
String shippingCharges=jsonObject.getString("shippingCharges");
JSONArray productDetails=jsonObject.getJSONArray("productDetails");
for (int j=0;j<productDetails.length();j++){
JSONObject prdet=productDetails.getJSONObject(j);
String productId=prdet.getString("productId");
Log.e("productId",productId);
JSONObject optionDetails=prdet.getJSONObject("optionDetails");
String optionId=optionDetails.getString("optionId");
Log.e("optionId",optionId);
JSONObject userAddressDetails= jsonObject.getJSONObject("userAddressDetails");
String email=userAddressDetails.getString("email");
Log.e("email",email);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_LONG).show();
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);