动态键 json 从 Web 服务获取响应



下面是 Web 服务 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 获得响应?

它与改造无关,而是gson。您正在使用 gson ( GsonConverterFactory ( 解析,而不是改造。,也许您应该为此模型注册TypeAdapter并手动执行此操作。

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

您可以在下面找到另一个动态键 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) {
                }
            });

我得到了一个解决方案,请查看我的答案;

网络服务.java(接口(

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

元素.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;
    }
}
}

在回收器视图中为集合数据创建了一个模型

数据模型.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 + ''' +
            '}';
}
}

网络服务调用

 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);
        }
    }
}
}

相关内容

  • 没有找到相关文章

最新更新