我有一个像这样的json数组
{
"success":"true",
"crops": {
"Brinjal":[---varieties of brinjal---],
"apple":[---varieties of apple---],
.................
.................
}
}
所以我得到了完整的作物......
JSONObject jsonObject;
jsonObject.getString("crops")
但我实际上需要创建两个数组,如
String[] crops = {"Brinjal","apple"};
String[] varities = {"---Brinjal Varities---","---apple varities---"};
如何生成这两个数组 如果我生成“作物”,那么我可以生成其他数组.... 那我怎么能产生“作物”......
答案 0 :(得分:4)
你应该这样做:
JSONObject obj = new JSONObject(jsonStringResp);
JSONObject cropsObj = obj.getJSONObject("crops");
JSONArray arr1 = subObject.getJSONArray("Brinjal");
然后迭代JSON数组并创建String数组。 希望它可以帮到你。
答案 1 :(得分:1)
public static void main(String[]args){
String joson = "{\n" +
" \"success\":\"true\",\n" +
" \"crops\": {\n" +
" \"Brinjal\":[---varieties of brinjal---],\n" +
" \"apple\":[---varieties of apple---],\n" +
" .................\n" +
" .................\n" +
" }\n" +
"}";
List<Object> apple = new ArrayList<Object>();
List<Object> Brinjal = new ArrayList<Object>();
apple.add("---varieties of apple---");
Brinjal.add("---varieties of brinjal---");
Map<String,Object> mapF = new HashMap<String,Object>();
Map<String,Object> mapS = new HashMap<String,Object>();
mapS.put("Brinjal", Brinjal);
mapS.put("apple", apple);
mapF.put("success", "true");
mapF.put("crops",mapS );
JSONObject obj = new JSONObject().fromObject(mapF);
System.out.println(obj);
JSONObject objF = obj.getJSONObject("crops");
String[] ListF = {};
String str = objF.keySet().toString();
String strF = str.substring(1, str.length()-1);
ListF = strF.split(", ");
List<Object> lsitF = new ArrayList<Object>();
for(int i = 0;i<ListF.length;i++){
lsitF.add(objF.get(ListF[i]));[enter image description here][1]
}
System.out.println(str);
System.out.println(lsitF.toString());
}
希望它对你有所帮助。
答案 2 :(得分:0)
试试这个:
String joson = "{\n" +
" \"success\":\"true\",\n" +
" \"crops\": {\n" +
" \"Brinjal\":[---varieties of brinjal---],\n" +
" \"apple\":[---varieties of apple---],\n" +
" .................\n" +
" .................\n" +
" }\n" +
"}";
List<String> whereCrops = new ArrayList<String>();
List<String> whereVarities = new ArrayList<String>();
String[] crops;
String[] varities;
ArrayList<String> contentKey = new ArrayList<String>();
try {
JSONObject myObject = new JSONObject(joson);
JSONObject jsonCrops = myObject.getJSONObject("crops");
Iterator<String> iter = jsonCrops.keys();
while (iter.hasNext()) {
String key = iter.next();
whereCrops.add(key);
Log.e("inningskey", key);
try {
JSONArray array = jsonCrops.getJSONArray(key);
whereVarities.add(array.toString());
} catch (JSONException e) {
// Something went wrong!
}
}
// here ! you need convert whereCrops to crops
} catch (JSONException e) {
e.printStackTrace();
}
}