简体   繁体   English

如何在Java(Android App)中修改Json结构?

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

I'm developing an Android application that consumes data from a Json API. 我正在开发一个使用Json API数据的Android应用程序。 That Json API returns a array of objects like this: 该Json API返回的对象数组如下所示:

[
  {
    "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. 如您所见,API返回两个具有相同ID但价格不同的对象。

I want to implement a solution that I can modify this json to something like this: 我想实现一个解决方案,可以将该json修改为如下形式:

[
  {
    "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. 如果需要的话,那就是我的WebServiceManager,我正在使用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: 在您的JSON响应上进行迭代并使用以下逻辑:

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. 如果确实存在,并且价格ID也存在,则覆盖价格。 If it does exist and the price ID doesn't exists, add the price to the map. 如果价格确实存在并且价格ID不存在,则将价格添加到地图中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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