Динамический ключ json получить ответ от WebService? - PullRequest
0 голосов
/ 26 марта 2019

Ниже приведен URL-адрес веб-сервиса:

{  
 "Status":"Success",
 "StatusCode":"200",
 "Message":"data fetch successfully.",
 "Data":{  
  "1":{  
     "OptionGroupName":"OPTION",
     "OptionGroupId":"122",
     "OptionCount":2,
     "Options":[  
        {  
           "OptionGroupId":"122",
           "OptionGroupName":"Option",
           "ProductId":"2861",
           "OptionId":"329",
           "OptionName":"Hot",
           "OptionPrice":"4.00",
           "IsActive":"1"
        },
        {  
           "OptionGroupId":"122",
           "OptionGroupName":"Option",
           "ProductId":"2861",
           "OptionId":"330",
           "OptionName":"Ice",
           "OptionPrice":"4.30",
           "IsActive":"1"
        }
     ]
  }
 }
}

Ниже представлен класс модели;

public class Elements{

@SerializedName("Data")
@Expose
private Map<String, Data> Data;

public Map<String, Data> getFeeds() {
    return Data;
}

public void setFeeds(Map<String, Data> Data) {
    this.Data = Data;
}

public class Data {
    @SerializedName("OptionGroupName")
    @Expose
    private String OptionGroupName;

    public String getOptionGroupName() {
        return OptionGroupName;
    }

    public void setOptionGroupName(String optionGroupName) {
        OptionGroupName = optionGroupName;
    }
}

}

Ниже приведен код для получения ответа;

  Map<String, String> jsonObject = new HashMap<>();
    jsonObject.put("productid", "2861");
    jsonObject.put("multiple", "1");

    ApiHandler.getApiService().place_order(jsonObject,
            new Callback<Elements>() {
                @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                @Override
                public void success(Elements placeOrderModel, Response
                        response) {

                    Log.e("response.getElemDetails()",""+response.getBody());
                    Gson gson = new Gson();
                    Elements myObj  = gson.fromJson(response.toString(),
                            new TypeToken<Elements>(){}.getType());


                    for (int i=0;i<myObj.getFeeds().size();i++)
                    {
                        Log.e("data",""+myObj.getFeeds().get(i).getOptionGroupName());
                    }
                }

                @Override
                public void failure(RetrofitError error) {

                }
            });

Я не могу разобрать json с классом модели. Как получить ответ с помощью динамического ключа JSON с помощью модернизации?

Ответы [ 3 ]

0 голосов
/ 26 марта 2019

Я получил решение, пожалуйста, просмотрите мой ответ;

WebServices.java (Интерфейс)

public interface Webservices {
@POST("/******.php?request=******")
@FormUrlEncoded
void place_order(@FieldMap Map<String, String> params, Callback<Elements> callback);
}

Elements.java

public class Elements{

@SerializedName("Data")
@Expose
private Map<String, Data> Data;

public Map<String, Data> getFeeds() {
    return Data;
}

public void setFeeds(Map<String, Data> Data) {
    this.Data = Data;
}

public class Data {
    @SerializedName("OptionGroupName")
    @Expose
    private String OptionGroupName;

    public String getOptionGroupName() {
        return OptionGroupName;
    }

    public void setOptionGroupName(String optionGroupName) {
        OptionGroupName = optionGroupName;
    }

    @Override
    public String toString() {
        return "Data{" +
                "OptionGroupName='" + OptionGroupName + '\'' +
                '}';
    }

    @SerializedName("Options")
    @Expose
    ArrayList<OptionsList> Options;

    public ArrayList<OptionsList> getOptions() {
        return Options;
    }

    public void setOptions(ArrayList<OptionsList> options) {
        Options = options;
    }
}

@Override
public String toString() {
    return "Elements{" +
            "Data=" + Data +
            '}';
}

public class OptionsList {
    @SerializedName("OptionName")
    @Expose
    private String OptionName;

    public String getOptionGroupName() {
        return OptionName;
    }

    public void setOptionGroupName(String OptionName) {
        OptionName = OptionName;
    }
}
}

Создана одна модель для набора данных в Recyclerview

DataModel.java

public class DataModel
{
String key,baseOptionGroupName,optionGroupName;

DataModel(String key,String baseOptionGroupName,String optionGroupName)
{
    this.key=key;
    this.baseOptionGroupName=baseOptionGroupName;
    this.optionGroupName=optionGroupName;
}

public String getKey() {
    return key;
}

public void setKey(String key) {
    this.key = key;
}

public String getBaseOptionGroupName() {
    return baseOptionGroupName;
}

public void setBaseOptionGroupName(String baseOptionGroupName) {
    this.baseOptionGroupName = baseOptionGroupName;
}

public String getOptionGroupName() {
    return optionGroupName;
}

public void setOptionGroupName(String optionGroupName) {
    this.optionGroupName = optionGroupName;
}

@Override
public String toString() {
    return "DataModel{" +
            "key='" + key + '\'' +
            ", baseOptionGroupName='" + baseOptionGroupName + '\'' +
            ", optionGroupName='" + optionGroupName + '\'' +
            '}';
}
}

Веб-сервис Call

 public class MainActivity extends AppCompatActivity {

DataModel dataModel ;
ArrayList<DataModel> dataModelArrayList = new ArrayList<>();
RecyclerView rvHistoryList;
HistoryAdapter historyAdapter;

//    {"Status":"Success","StatusCode":"200","Message":"data fetch successfully.","Data":{"1":{"OptionGroupName":"CHOICE OF MEAT'S","OptionGroupId":"227","OptionCount":3,"Options":[{"OptionGroupId":"227","OptionGroupName":"Choice of Meat's","ProductId":"3426","OptionId":"1032","OptionName":"Ground Beef","OptionPrice":"0.00","IsActive":"1","group_id":"0"},{"OptionGroupId":"227","OptionGroupName":"Choice of Meat's","ProductId":"3426","OptionId":"1033","OptionName":"Chicken","OptionPrice":"0.00","IsActive":"1","group_id":"0"},{"OptionGroupId":"227","OptionGroupName":"Choice of Meat's","ProductId":"3426","OptionId":"1034","OptionName":"Pork Patty","OptionPrice":"0.00","IsActive":"1","group_id":"0"}]},"2":{"OptionGroupName":"CHOICE OF SAUCE","OptionGroupId":"228","OptionCount":8,"Options":[{"OptionGroupId":"228","OptionGroupName":"Choice of Sauce","ProductId":"3426","OptionId":"1035","OptionName":"Tomato Sauce","OptionPrice":"0.00","IsActive":"1","group_id":"0"},{"OptionGroupId":"228","OptionGroupName":"Choice of Sauce","ProductId":"3426","OptionId":"1036","OptionName":"BBQ Sauce","OptionPrice":"0.00","IsActive":"1","group_id":"0"},{"OptionGroupId":"228","OptionGroupName":"Choice of Sauce","ProductId":"3426","OptionId":"1037","OptionName":"Mustard American Sauce","OptionPrice":"0.00","IsActive":"1","group_id":"0"},{"OptionGroupId":"228","OptionGroupName":"Choice of Sauce","ProductId":"3426","OptionId":"1038","OptionName":"Aloli Sauce","OptionPrice":"0.00","IsActive":"1","group_id":"0"},{"OptionGroupId":"228","OptionGroupName":"Choice of Sauce","ProductId":"3426","OptionId":"1039","OptionName":"Sweet Chilli Sauce","OptionPrice":"0.00","IsActive":"1","group_id":"0"},{"OptionGroupId":"228","OptionGroupName":"Choice of Sauce","ProductId":"3426","OptionId":"1040","OptionName":"Chilli Sauce","OptionPrice":"0.00","IsActive":"1","group_id":"0"},{"OptionGroupId":"228","OptionGroupName":"Choice of Sauce","ProductId":"3426","OptionId":"1041","OptionName":"Mayonaise","OptionPrice":"0.00","IsActive":"1","group_id":"0"},{"OptionGroupId":"228","OptionGroupName":"Choice of Sauce","ProductId":"3426","OptionId":"1042","OptionName":"No Sauce","OptionPrice":"0.00","IsActive":"1","group_id":"0"}]}}}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    rvHistoryList = findViewById(R.id.rvHistoryList);

    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(MainActivity.this);
    rvHistoryList.setLayoutManager(mLayoutManager);
    rvHistoryList.setItemAnimator(new DefaultItemAnimator());

    Map<String, String> jsonObject = new HashMap<>();
    jsonObject.put("productid", "3426");
    jsonObject.put("multiple", "1");

    ApiHandler.getApiService().place_order(jsonObject,
            new Callback<Elements>() {
                @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                @Override
                public void success(Elements placeOrderModel, Response
                        response) {

                    Map<String, Elements.Data> entityList = placeOrderModel.getFeeds();

                    for (String mapKey : entityList.keySet()) {

                        Log.e("Map", "mapKey : " + mapKey + " , mapValue : " + entityList.get(mapKey).getOptionGroupName());


                        for (int i = 0; i < entityList.get(mapKey).getOptions().size(); i++) {
                            Log.e("!!!!!!!!!!!!!", "" + entityList.get(mapKey).getOptions().get(i).getOptionGroupName());

                            dataModel = new DataModel(mapKey,entityList.get(mapKey).getOptionGroupName(),entityList.get(mapKey).getOptions().get(i).getOptionGroupName());
                            dataModelArrayList.add(dataModel);
                        }


                    }

                    historyAdapter = new HistoryAdapter(dataModelArrayList);
                    rvHistoryList.setAdapter(historyAdapter);


                    Log.e("AAAAAAAAAAAAAAAAAAAAAA", "" + dataModelArrayList.toString());

                }

                @Override
                public void failure(RetrofitError error) {

                }
            });
}

public class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.ViewHolder> {
    private ArrayList<DataModel> mDataset;

    public HistoryAdapter(ArrayList<DataModel> reviwsLists) {
        mDataset = reviwsLists;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_history, parent, false);

        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element
        holder.tv1.setText(mDataset.get(position).getKey());
        holder.tv2.setText(mDataset.get(position).getBaseOptionGroupName());
        holder.tv3.setText(mDataset.get(position).getOptionGroupName());
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public View mainView;
        TextView tv1, tv2,tv3;

        public ViewHolder(View v) {
            super(v);
            mainView = v;
            tv1 = v.findViewById(R.id.tv1);
            tv2 = v.findViewById(R.id.tv2);
            tv3 = v.findViewById(R.id.tv3);
        }
    }
}

}
0 голосов
/ 19 июня 2019

Вы можете найти другой ответ ниже для динамического ключа json fetch response

JSON

  {  
   "tom@example.com":{  
  "_from":"giles@gmail.com",
  "message":{  
     "from":"giles@gmail.com",
     "detail":"AnyonewanttomeetmeinParis"
  }
  },
 "harry@example.com":{  
  "_from":"giles@gmail.com",
  "message":{  
     "from":"giles@gmail.com",
     "detail":"AnyonewanttomeetmeinParis"
  }
  }
 }

Вызов веб-сервиса

        ApiHandler.getApiService().place_order2(
            new Callback<Object>() {
                @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                @Override
                public void success(Object placeOrderModel, Response
                        response) {

                    Log.e("WWWWWWWWWWWWWWWWWWW",""+placeOrderModel.toString());
                    JSONObject jsonData = null;
                    try {
                        jsonData = new JSONObject(placeOrderModel.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Iterator itr = jsonData.keys();
                    while(itr.hasNext()) {
                        String keys = (String) itr.next();
                        Log.e("Keys", "----" + keys);

                        try {
                            JSONObject issue = jsonData.getJSONObject(keys);
                            String _pubKey = issue.optString("_from");
                            Log.e("_from", "----" + _pubKey);

                            dataModel = new DataModel(keys,_pubKey);
                            dataModelArrayList.add(dataModel);

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

                    historyAdapter = new HistoryAdapter(dataModelArrayList);
                    rvHistoryList.setAdapter(historyAdapter);
                }

                @Override
                public void failure(RetrofitError error) {

                }
            });
0 голосов
/ 26 марта 2019

Это не связано с модернизацией, кроме GSON.Вы анализируете с помощью gson (GsonConverterFactory), а не модифицируете.и, вероятно, вам следует зарегистрировать TypeAdapter для этой модели и сделать это вручную.

https://google.github.io/gson/apidocs/com/google/gson/TypeAdapter.html

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...