简体   繁体   中英

How to modify Json structure in java (Android App)?

I'm developing an Android application that consumes data from a Json API. That Json API returns a array of objects like this:

[
  {
    "idProduct": 1,
    "price": 25.9,
    "tpPrice": v1
  },
  {
    "idProduct": 1,
    "price": 29.9,
    "tpPrice": v2
  },
  {
    "idProduct": 2,
    "price": 19.9,
    "tpPrice": v1
  },
  {...}
]

As you can see, the API returns two objects with the same ID, but with different prices.

I want to implement a solution that I can modify this json to something like this:

[
  {
    "idProduct": 1,
    "prices": [
      {
        "price": "25.9,
        "tpPrice": v1
      },
      {
        "price": "29.9,
        "tpPrice": v2
      }
    ]
  },
  {
    "idProduct": 2,
    "prices" [
      {
        "price": "19.9,
        "tpPrice": v1
      }
    ]
  },
  {...}
]

Thats my WebServiceManager if its necessary, I'm using Gson.

public class WebServiceManager extends AsyncTask<String, String, List<Object>> {

   private IWebServiceManager iWebServiceMngr;

   private Context ctx;
   private ProgressDialog progress;
   private String messageError = null;
   private String bean = null;
   //private final String URL = "http://192.168.7.1:8080/WSPrePedidos/api/consulta/";
   private final String URL_BASE = "/WSPrePedidos/api/consulta/";
   private final String PATH = "br.com.example.model.";

   @Override
   protected void onPreExecute() {
       super.onPreExecute();

       progress = new ProgressDialog(ctx);
       progress.setCancelable(false);
       progress.setMessage(ctx.getString(R.string.progress_start));
       progress.show();
   }

   /**
    * 0 - Access
    * 1 - Parameters
    * 2 - Class
    *
    * @param params
    * @return
    */
   @Override
   protected List<Object> doInBackground(String... params) {

       bean = params[2].toString();
       publishProgress(ctx.getString(R.string.progress_middle));

       HttpURLConnection urlConnection = null;
       BufferedReader reader = null;
       List<Object> lstObj = new ArrayList<>();
       try {
           URL url = new URL(params[0] + URL_BASE + params[1]);
           Log.i("URL: ", url.toString());
           urlConnection = (HttpURLConnection) url.openConnection();
           urlConnection.setRequestMethod("GET");
           urlConnection.setConnectTimeout(50000);
           urlConnection.setReadTimeout(50000);
           urlConnection.connect();

           int cdResposta = urlConnection.getResponseCode();

           InputStream inputStream;
           if (cdResposta < HttpURLConnection.HTTP_BAD_REQUEST) {
               Log.i("InputStream Ok: ", "" + cdResposta);
               inputStream = urlConnection.getInputStream();
           } else {
               Log.i("InputStream ferrado: ", "" + cdResposta);
               inputStream = urlConnection.getErrorStream();
               messageError = ctx.getString(R.string.message_fail_generic);
           }

           reader = new BufferedReader(new InputStreamReader(inputStream));

           JsonElement je = new JsonParser().parse(reader);
           Gson gson = new Gson();
           if (!je.isJsonObject()) {
               for (JsonElement element : je.getAsJsonArray()) {
                   lstObj.add(gson.fromJson(element.getAsJsonObject(), Class.forName(PATH + bean)));
               }
           } else if (je.isJsonObject()) {
               messageError = null;
               JsonObject jsonObject = je.getAsJsonObject();
               if (jsonObject.get("error") == null) {
                   lstObj.add(gson.fromJson(je.getAsJsonObject(), Class.forName(PATH + bean)));
               }
           }


       } catch (Exception e) {
           e.printStackTrace();
           messageError = ctx.getString(R.string.message_fail_connect_server);
       } finally {
           try {
               if (urlConnection != null)
                   urlConnection.disconnect();
               if (reader != null)
                   reader.close();
           } catch (IOException e1) {
               //e1.printStackTrace();
           }
       }

       return lstObj;
   }

   @Override
   protected void onProgressUpdate(String... params) {
       progress.setMessage(params[0]);
   }

   @Override
   protected void onPostExecute(List<Object> lstObj) {
       super.onPostExecute(lstObj);

       iWebServiceMngr.posExecuteAsyncTaskResult(lstObj, bean, messageError);
       progress.dismiss();
   }

   public WebServiceManager(Context ctx, IWebServiceManager iWebServiceMngr) {
       this.ctx = ctx;
       this.iWebServiceMngr = iWebServiceMngr;
   }
}
  • Sorry for my bad english.
  • I tried to be as specific as possible.

Create a "Product" Object that contains a map of prices. On your JSON response iterate through it and use the logic:

If a product doesn't exist, create the product and apply the price. If it does exist and the price ID also does, overwrite the price. If it does exist and the price ID doesn't exists, add the price to the map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM