2014-11-12 9 views
0

[{id:1, name:a}{id:2, name:b}] 형식의 json 응답이 있습니다. 스피너에 이름 값 (a, b ..)을 넣고 싶습니다. 회 전자에서 항목을 선택하면 'a'라고 말하고 '1'인 id 값을 가져와야합니다. 어떻게 할 수 있습니까? 이것 좀 도와주세요. 예제가 도움이 될 것입니다.android에서 JSON 배열 구문 분석

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` 
+2

여기에 코드를 게시하십시오. –

+0

시도해 보셨습니까? –

+0

arraylist를 만들고 for 루프를 사용하여 JSONArray를 구문 분석하여 요소 (a, b, c 등)를 추가합니다. 그런 다음 Arraylist를 사용하여 회 전자를 채 웁니다. –

답변

3

당신은 당신이 코드 snippits를 제공해야 미래에, 그러나이

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

같은 데이터로 사용 가능한 스피너를 만들 수 있습니다, 그것은 질문한다 대답하기가 훨씬 쉽습니다! :)

+0

저는 실제로 당신이 말하는 것을 완전히 이해합니다. 하지만 위의 코드를 사용하면 선택한 ID에 해당하는 ID를 가져올 수 없습니다. 내가 현재 갖고있는 코드 스 니펫을 붙이자. – user3782869

+0

@ user3782869 네, 여기에 코드를 붙여 넣으면 문제를 해결할 수 있는지 알 수 있습니다! 이름으로 ASWELL ID를 가져 오려면 id 속성과 name 속성을 사용하여 사용자 지정 개체를 만들어야 할 수도 있습니다. 그런 다음 해당 객체를 처리 할 어댑터를 만들고 해당 어댑터에 회 전자의 어댑터를 설정해야합니다. 그것들 중 하나에 대한 어댑터를 생성했다면 listview와 유사합니다. – Chackle

0

가정 JSON 형식 :

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

비슷한 문제이므로, 이렇게 해결했습니다. 먼저 데이터 전송 객체 (예 : getter 및 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; 
    } 
} 

는 그런 다음 JSON 문자열이 당신을 도움이되기를 바랍니다

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

} 
} 

MainActivity

에서 사용할 수

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

가} 가정 할 때,이 같은 사용자 정의 스피너 어댑터를 만들 수 있습니다.