如何拆分String并将值与另一个值相关联?

时间:2013-04-30 09:14:09

标签: android string

抱歉,刚看到你的答案,我一直在做一些代码: 这是我的代码:

ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();


        JSONObject mainJson = new JSONObject(reply);



            JSONArray jsonArray = mainJson.getJSONArray("Companies");



            for (int i = 0; i < jsonArray.length(); i++) {

                HashMap<String, String> map = new HashMap<String, String>();

                 JSONObject objJson = jsonArray.getJSONObject(i);

                 map.put("ID", objJson.getString("CompanyID"));
                 map.put("name", objJson.getString("CompanyName"));
                 mylist.add(map);



                 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item);
                 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                 spinner.setAdapter(adapter);

但是日志说错误解析数据or.json.exception !!

1 个答案:

答案 0 :(得分:0)

您可以使用:

    class result {
       item[] items;
    }
    class item {
       int id;
       String name;
    }
    private class itemSerializer implements JsonSerializer<item> {
    @Override
            public User deserialize(JsonElement json, Type type,
    JsonDeserializationContext context) throws JsonParseException {
            JsonObject jobject = (JsonObject) json;
            item it = new item();
            it.id = jobject.get("id").getAsInt(), 
            it.name =  jobject.get("name").getAsString()); 
            return it;
           }
    }

com.google.gson.GsonBuilder gson = new GsonBuilder();

    // and to serialize only id and name use custo deserializer:

    gson.registerTypeAdapter(item.class, new itemSerializer());
    result res = new result();
    res = gson.create().fromJson(yourString, res.getClass());

然后你必须加载List&lt; String&gt;将名称命名为Splitter的ArrayAdapter,可能还有HashMap&lt; String,String&gt; mapNames2Ids to map名称点击了id