简体   繁体   中英

Parsing JSON array in android

I have a json response in the format [{id:1, name:a}{id:2, name:b}] . I want to put name values(a, b..) in the spinner. If I select an item in the spinner lets say 'a' I need to get the id value that is 1. How can I do that? Please help me on this. Examples will be helpful.

    createworkorder.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            try {
                HttpClient httpclient = new DefaultHttpClient();
                String url = "http://192.168.10.60:8095/tmanager/city?";
                url = url.replace(" ", "%20");
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entityres = response.getEntity();
                isX = entityres.getContent();
                response_string = Utils1.getResponse(isX);

            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection " + e.toString());
                System.out.println("Error in http connection "
                        + e.toString());
            }

            allCities = new ArrayList<String>();

            try {
                cityArray = new JSONArray(response_string);

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

                    JSONObject obj = cityArray.getJSONObject(i);
                    Iterator<String> it = obj.keys();

                    String str = it.next().toString().trim();
                    Log.v("str is", str);

                    allCities.add(str);

                    intent = new Intent(CreateOpenWO.this,
                            CreateWorkOrder.class);
                    startActivity(intent);

                }

            } catch (JSONException e) {
                Log.e("JSON", "There was an error parsing the JSON", e);
            }

        }
    });`enter code here`

You can create a usable spinner with your data like this

Spinner yourSpinner = (Spinner) findViewById(R.id.yourSpinnerId);

ArrayList<String> yourSpinnerData = new ArrayList<String>();
String yourJsonString = "[{id:1, name:'a'},{id:2, name:'b'}]";

try {
    JSONArray jsonArray = new JSONArray(yourJsonString);
    for (int i = 0; i < jsonArray.length(); i++)
    {
        JSONObject jsonObject = jsonArray.getJsonObject(i);
        int id = jsonObject.getInt("id");
        String name = jsonObject.getString("name");
        // do things with the values you pull here!
        yourSpinnerData.add(name);
    }
}
catch (JSONException e)
{
    e.printStackTrace();
}

// Use spinner data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
 android.R.layout.simple_spinner_item, yourSpinnerData);
yourSpinner.setAdapter(adapter);

However, in future you should provide code snippits, it makes questions a lot easier to answer! :)

Assuming JSON format:

String s = "[{id:1, name:'a'}, {id:2, name:'b'}]";
        JSONArray ja;
        try {
            ja = new JSONArray (s);
            for (int i = 0; i < ja.length (); i++) {
                JSONObject jObj = ja.getJSONObject (i);
                jObj.get ("memberName");
            }
        }
        catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Similar problem , I solved like this. First , create Data Transfer Object like this,(Its simply a getter and setter).

public class NameCodeDTO {
private  int id;
private int code;
private String name;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getCode() {
    return code;
}

public void setCode(int code) {
    this.code = code;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
    }
}

Then create a custom spinner adapter like this,

public class SpinnerNameCodeAdapter extends ArrayAdapter<NameCodeDTO> {

private Context mContext;
private List<NameCodeDTO> nameCodeDTOList;
private int layoutId;
LayoutInflater inflater=null;

public SpinnerNameCodeAdapter(Context mContext, int resource,List<NameCodeDTO>nameCodeDTOList) {
    super(mContext, resource,nameCodeDTOList);
    this.mContext=mContext;
    this.layoutId=resource;
    this.nameCodeDTOList=nameCodeDTOList;
    inflater=(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return nameCodeDTOList.size();
}


@Override
public long getItemId(int position) {
    return position;
}

@Override
public NameCodeDTO getItem(int position) {
    return nameCodeDTOList.get(position);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    return getCustomView(position, convertView, parent);
}


@Override
public View getDropDownView(int position, View view, ViewGroup parent) {

  return getCustomView(position,view,parent);
}

public View getCustomView(int position, View view, ViewGroup parent){
    ViewHolder holder=new ViewHolder();

    if(view==null){
        view = inflater.inflate(layoutId, null, false);

        holder.spinnerText=(TextView)view.findViewById(R.id.tv_simple_spinner);
        view.setTag(holder);
    }else{
        holder = (ViewHolder) view.getTag();
    }

    NameCodeDTO nameCodeDTO=nameCodeDTOList.get(position);
    holder.spinnerText.setText(nameCodeDTO.getName());
    return view;
}

public class ViewHolder{
    TextView spinnerText;
}

}

Assuming that json string is available in MainActivity

public class MainActivity extends Activity implements OnItemSelectedListener{

private Spinner mySpinner;
List<NameCodeDTO> nameIdList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    mySpinner=(Spinner)findViewById(R.id.my_spinner);
    mySpinner.setOnItemSelectedListener(this);



    //do json parsing here for json structure [{id:1, name:a}{id:2, name:b}]

    nameIdList=new Array<NamecodeDTO>();

    JSONArray ja;


    try {
        ja = new JSONArray (s);
        for (int i = 0; i < ja.length (); i++) {
            JSONObject jObj = ja.getJSONObject (i);
            String name=jObj.getString("name");
            String id=jObj.getString("id");

            NameCodeDTO nameCodeDTO= new NameCodeDTO();
            nameCodeDTO.setName(name);
            nameCodeDTO.setId(id);

            nameIdList.add(NameCodeDTO);

        }
    }
    catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    //you_spinner_text.xml layout has TextView with id is tv_spinner_simple

    mySpinner.setAdapter(new SpinnerNameCodeAdapter (this,R.id.your_spinner_text, nameIdList));

}


@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {



      NameCodeDTO nameId=(NameCodeDTO)(adapterView).getItemAtPosition(position);
   // this gives the desired answer
        Log.i("spinner name::",nameId.getName());
        Log.i("spinner id::", nameId.getId());

 }
}

Hope this helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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