简体   繁体   English

Android和JSON解析

[英]Android and json parsing

I have an android application which gets a json string. 我有一个获取json字符串的android应用程序。

[
{
    "apellidos": "seguro",
    "edad": 2,
    "idninos": 1,
    "nombre": "antonio",
    "padres": "n1"
},
{
    "apellidos": "martinez",
    "edad": 2,
    "idninos": 2,
    "nombre": "sebastian",
    "padres": "n2"
},
{
    "apellidos": "lopez",
    "edad": 2,
    "idninos": 3,
    "nombre": "francisaca",
    "padres": "n3"
},
{
    "apellidos": "maroto",
    "edad": 2,
    "idninos": 4,
    "nombre": "gregoria",
    "padres": "n4"
},
{
    "apellidos": "maroto",
    "edad": 2,
    "idninos": 5,
    "nombre": "javier",
    "padres": "n4"
},
{
    "apellidos": "ramirez",
    "edad": 1,
    "idninos": 6,
    "nombre": "andrea",
    "padres": "n5"
},
{
    "apellidos": "leal",
    "edad": 1,
    "idninos": 7,
    "nombre": "jorge",
    "padres": "n6"
},
{
    "apellidos": "rodriguez",
    "edad": 2,
    "idninos": 8,
    "nombre": "antonio",
    "padres": "n7"
},
{
    "apellidos": "gomez",
    "edad": 2,
    "idninos": 9,
    "nombre": "jaime",
    "padres": "n8"
},
{
    "apellidos": "jimenez",
    "edad": 2,
    "idninos": 10,
    "nombre": "nerea",
    "padres": "n9"
},
{
    "apellidos": "gutierrez",
    "edad": 2,
    "idninos": 11,
    "nombre": "paquito",
    "padres": "n12"
},
{
    "apellidos": "esteso",
    "edad": 2,
    "idninos": 12,
    "nombre": "tomas",
    "padres": "n15"
}
]

And I show it in this way:I show in a listview ; 我以这种方式显示它:我在listview

public class MainActivity extends ListActivity {
private static final String LOGTAG = "LogsAndroid";  
static String id;
   EditText eTetx1;
//contexto
private Context context;
//url
private static String    

   url="http://192.168.1.33:8080/WSBaby1/webresources/com.gleegoo.ws.ninos/";
//variable de json
private static final String TAG_NOMBRE="nombre";
private static final String TAG_APELLIDO="apellidos";
//lista arrays desplegables
ArrayList<HashMap<String,String>> jsonlist= new ArrayList<HashMap<String,String>>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //llamando la actividad
    new GetJSONActivity(MainActivity.this).execute();
     eTetx1 = (EditText)  findViewById(R.id.editText1);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
private class GetJSONActivity extends AsyncTask<String, Void, String>{
    private ListActivity activity;


    public GetJSONActivity(ListActivity activity){
        this.activity=activity;
        context = activity;
    }

    @Override
    protected String doInBackground(String... params) {

        JSONParser jParser = new JSONParser();
        //getting JSON string from url
        JSONArray json = jParser.GetJSONfromUrl(url);
        for (int i = 0; i < json.length(); i++) {
            try {
                JSONObject c = json.getJSONObject(i);
                String vpeli=c.getString(TAG_NOMBRE);
                String apell=c.getString(TAG_APELLIDO);

                HashMap<String, String> map = new HashMap<String, String>();
                //
                map.put(TAG_NOMBRE, vpeli);
                map.put(TAG_APELLIDO, apell);
                jsonlist.add(map);

            } catch (JSONException e) {
                // TODO: handle exception
                e.printStackTrace();
                return "Error creando variables";
            }
        }
        return "EXITO";
    }

   @Override
   protected void onPostExecute(String success){
       ListAdapter adapter = new SimpleAdapter(context, jsonlist,R.layout.items, new String[] {TAG_NOMBRE,TAG_APELLIDO}, new int[]{R.id.nombre,R.id.tipo});
    setListAdapter(adapter);
    //selecting single listview
    getListView();
   }

Well, this works perfectly, my problem is this: If I want to show, for example all data from an id, idnino 好吧,这很好用,我的问题是这样的:如果我想显示,例如ID中的所有数据,idnino

eg 3. {"apellidos":"lopez","edad":2,"idninos":3,"nombre":"francisaca","padres":"n3"} 例如3。 {"apellidos":"lopez","edad":2,"idninos":3,"nombre":"francisaca","padres":"n3"}

He had thought about changing the url and put this: 他曾考虑过更改网址 ,并输入以下内容:

private static String url="http://192.168.1.33:8080/WSBaby1/webresources/com.gleegoo.ws.ninos/3

But I get it but can not show it .. This is my logcat: 但是我明白了,但无法显示..这是我的日志:

  04-01 12:43:51.165: E/JSON Parser(17792): Error traduciendo    
datosorg.json.JSONException: Value  
{"nombre":"francisaca","padres":"n3","idninos":3,"apellidos":"lopez","edad":2} of type   
 org.json.JSONObject cannot be converted to JSONArray
 04-01 12:43:51.175: W/dalvikvm(17792): threadid=12: thread exiting with uncaught    
exception (group=0x419612a0)
04-01 12:43:51.240: E/AndroidRuntime(17792): FATAL EXCEPTION: AsyncTask #1
04-01 12:43:51.240: E/AndroidRuntime(17792): java.lang.RuntimeException: An error  
occured while executing doInBackground()
04-01 12:43:51.240: E/AndroidRuntime(17792):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
04-01 12:43:51.240: E/AndroidRuntime(17792):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
04-01 12:43:51.240: E/AndroidRuntime(17792):    at 
java.util.concurrent.FutureTask.setException(FutureTask.java:124)
04-01 12:43:51.240: E/AndroidRuntime(17792):    at         
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
04-01 12:43:51.240: E/AndroidRuntime(17792):    at  
java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-01 12:43:51.240: E/AndroidRuntime(17792):    at 
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-01 12:43:51.240: E/AndroidRuntime(17792):    at 
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
04-01 12:43:51.240: E/AndroidRuntime(17792):    at  
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
04-01 12:43:51.240: E/AndroidRuntime(17792):    at 
java.lang.Thread.run(Thread.java:856)
04-01 12:43:51.240: E/AndroidRuntime(17792): Caused by: java.lang.NullPointerException
04-01 12:43:51.240: E/AndroidRuntime(17792):    at 
com.example.jsonprueba.MainActivity$GetJSONActivity.doInBackground(MainActivity.java:65)
04-01 12:43:51.240: E/AndroidRuntime(17792):    at 
com.example.jsonprueba.MainActivity$GetJSONActivity.doInBackground(MainActivity.java:1)
04-01 12:43:51.240: E/AndroidRuntime(17792):    at 
android.os.AsyncTask$2.call(AsyncTask.java:287)
04-01 12:43:51.240: E/AndroidRuntime(17792):    at 
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-01 12:43:51.240: E/AndroidRuntime(17792):    ... 5 more

This is a JSONArray and not a JSONObject - to make a JSONObject from it, use 这是一个JSONArray而不是JSONObject要使用它创建JSONObject ,请使用

JSONObject jsonObject = jsonArray.getJSONObject(0);

this gets the first JSONObject from this JSONArray. 这从此JSONArray获取第一个JSONObject。

If you have multiple JSONObjects, use this: 如果您有多个JSONObject,请使用以下命令:

JSONObject jsonObject;
for(int n = 0; n < jsonArray.length(); n++)
{
    jsonObject = jsonArray.getJSONObject(n);
}

To get the values: 要获取值:

jsonObject.getString("name");

You are trying to parse the JSON as an Array 您正在尝试将JSON解析为数组

JSONArray json = jParser.GetJSONfromUrl(url);

but your JSON is an object 但您的JSON是一个对象

{
    "apellidos": "lopez",
    "edad": 2,
    "idninos": 3,
    "nombre": "francisaca",
    "padres": "n3"
}

your JSON should be an array with one object only 您的JSON应该是仅包含一个对象的数组

[{
    "apellidos": "lopez",
    "edad": 2,
    "idninos": 3,
    "nombre": "francisaca",
    "padres": "n3"
}]

you can try to check if the result object is an array or an object like this 您可以尝试检查结果对象是数组还是这样的对象

Object jsonResultObject = jParser.GetJSONfromUrl(url);

if (jsonResultObject!=null) {
    if (jsonResultObject instanceof JSONArray) {
        ......
    }else if (jsonResultObject instanceof JSONObject) {
        .....
    }else{
        throw new Exception("The result object is not a JSON object or an Array");
    }

}

Remove array from your coding and do it with object as the JSON you showed is of Objects and not of arrays. 从编码中删除数组,并使用object进行处理,因为您显示的JSON是Objects而不是array。

Arrays starts with [ ] Objects with { } 数组以[]开头,对象为{}

Your JSON starts with array and element inside it are in arrays. 您的JSON以数组开头,并且其中的元素位于数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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