1

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

    }

布局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>

谢谢

4

2 回答 2

1

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

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

JSONObject jsonObj = new JSONObject(result);
JSONArray ja = jsonObj.getJSONArray("ref_product_types")
于 2013-03-15T22:15:44.877 回答
1
{
   "ref_product_types": [
                          {"product_type_code":"1",
                           "product_type_description":"Mobile Phone"
                          },
                          {"product_type_code":"2",
                           "product_type_description":"Toys"
                          }
                        ]
}

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

所以首先你应该知道 multiset 括号{表示JSONObject和括号[表示JSONArray。所以你的字符串呈现 JSONObject 并存储 JSONArray。所以你需要先创建新的 JSONObject 然后解析 JSONArray。

JSONObject o = new JSONObject(sourceString);
JSONArray arr = o.getJSONArray("ref_product_types");
于 2013-03-15T22:27:21.787 回答