php android spinner - JSONObject无法转换为JSONArray

时间:2013-03-15 22:08:08

标签: php android mysql json

我是java编程的初学者,我试图将php结果加载到微调器中,我一直有这个问题,JSONObject无法转换为JSONArray。我在网站上搜索尝试转换它但我似乎无法修复它。

php结果:

{"ref_product_types":[{"product_type_code":"1","product_type_description":"Mobile Phone"},{"product_type_code":"2","product_type_description":"Toys"}]}

我在清单

中添加了这个
<uses-permission android:name="android.permission.INTERNET"/>

这是java代码:

package com.example.spinnert1;

public class Main extends Activity {

InputStream is=null;
String result=null;
String line=null;

String[] product_type_code, product_type_description;  

Spinner spinner1,spinner2;



@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
final List<String> list1 = new ArrayList<String>();
final List<String> list2 = new ArrayList<String>();

Button b=(Button) findViewById(R.id.button1);

b.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v)
{
                // TODO Auto-generated method stub

try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/epos_connect/get_all_product_type.php");
HttpResponse response = httpclient.execute(httppost);
Log.e("Fail 1", "3");

HttpEntity entity = response.getEntity();
Log.e("Fail 1", "4");

is = entity.getContent();
Log.e("Pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",Toast.LENGTH_LONG).show();
finish();
}    


try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}    


try
{
JSONArray JA=new JSONArray(result);


JSONObject json= null;
product_type_code = new String[JA.length()];       
product_type_description = new String[JA.length()];

for(int i=0;i<JA.length();i++)
{
json=JA.getJSONObject(i);
product_type_code[i] = json.getString("product_type_code");
product_type_description[i]=json.getString("product_type_description");
}
Toast.makeText(getApplicationContext(), "sss",Toast.LENGTH_LONG).show();

for(int i=0;i<product_type_code.length;i++)
{
list1.add(product_type_code[i]);
list2.add(product_type_description[i]);
}

spinner_fn();

}
catch(Exception e)
{

Log.e("Fail 3", e.toString());
//login.this.finish();

}
}
});

}
private void spinner_fn() {
    // TODO Auto-generated method stub

    ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(getApplicationContext(),
                                    android.R.layout.simple_spinner_item, product_type_code);
    dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(dataAdapter1);


    ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(getApplicationContext(),
                                    android.R.layout.simple_spinner_item, product_type_description);
    dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner2.setAdapter(dataAdapter2);


    spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
    {
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id)
    {
    // TODO Auto-generated method stub

    spinner2.setSelection(position);

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0)
    {
    // TODO Auto-generated method stub
    }

    });


    spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
    // TODO Auto-generated method stub

    spinner1.setSelection(position);

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub
    }
    });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }

    }

layout xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Spinner
    android:id="@+id/spinner1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/country_arrays"
    android:prompt="@string/country_prompt" />

<Spinner
    android:id="@+id/spinner2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<Button
    android:id="@+id/btnSubmit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Submit" />

</LinearLayout>

感谢

2 个答案:

答案 0 :(得分:1)

看起来返回的数据确实是JSON对象,而不是JSON数组; JSON数组嵌套在外部对象中的“ref_product_types”键中。

你会想要使用类似的东西:

JSONObject jsonObj = new JSONObject(result);
JSONArray ja = jsonObj.getJSONArray("ref_product_types")

答案 1 :(得分:1)

{
   "ref_product_types": [
                          {"product_type_code":"1",
                           "product_type_description":"Mobile Phone"
                          },
                          {"product_type_code":"2",
                           "product_type_description":"Toys"
                          }
                        ]
}

所以我做了一些格式化,以便你清楚地看到它。

首先,您应该知道多重括号 { 表示 JSONObject ,并且括号 [ 表示 JSONArray 即可。所以你的String呈现JSONObject并存储JSONArray。所以你需要先创建新的JSONObject,然后再解析JSONArray。

JSONObject o = new JSONObject(sourceString);
JSONArray arr = o.getJSONArray("ref_product_types");