Android的JSON解析和转换 [英] Android JSON Parsing And Conversion

查看:298
本文介绍了Android的JSON解析和转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好。

我试图 JSON数据解析为字符串,但我觉得我做错了什么:这里是部分

I am trying to parse JSON data into a string but I think I'm doing something wrong: here is the section.

private void read_JSON()
    {
    String JSON;
        JSONObject jso3 = new JSONObject(JSON);
        for (int i=0; i < jso3.length(); i++)
        {

        try
        {

            String name = jso3.getString("Nombre");
            String surname = jso3.getString("Apellidos");
            String date = jso3.getString("Año_nacimiento");
            String child_names = jso3.getString("Nombres_Hijos");


        }catch (JSONException e)
        {
            e.printStackTrace();
        }

        }
    jso3.toString(JSON);    
    }

我中创建的JSON 的MainActivity.java,它不是一个单独的文件。

I created the JSON within the MainActivity.java, it's not on a separate file.

下面是JSON创作的code:

Here is the code of the JSON creation:

private void create_JSON()
{
    JSONObject jso = new JSONObject();

    try {
        jso.put("Nombre","Miguel");
        jso.put("Apellidos", "Garcia");
        jso.put("Año_nacimiento", 1990);
        JSONArray jsa = new JSONArray();
        jsa.put("Blur");
        jsa.put("Clur");
        jso.put("Nombres_Hijos", jsa);

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

我毫不怀疑,认为 JSON 是正确创建的,我只需要了解我怎么分析它,并把它转换成一个字符串的帮助。

I have no doubts that the JSON is correctly created, I just need help in understanding how do I parse it and convert it into a String.

我将不胜感激,如果你能在我的编程指出我的缺点。

I would be very grateful if you could point out to me the flaws in my programming.

毛罗。

推荐答案

使用下面的选项,同时解析JSON避免常见错误。

Use the following options while parsing JSON to avoid common error.

JSONObject jso3 = new JSONObject(output);
String name = jso3.optString("Nombre",""); // here default value is blank ("")
String surname = jso3.optString("Apellidos",null);// here default value is null
int date = jso3.getInt("Año_nacimiento",0); // here default value is ZERO (0)
JSONArray menuObject = jso3.getJSONArray("Nombres_Hijos");
for(int i=0;i<menuObject.length;i++){   
System.out.println(menuObject.getString(i));
}

使用的选择选项可以设置默认返回值。事件如果JSON数据你会得到默认值不是可用的标记。

Using opt option you can set default return value. Event if that tag not available in JSON data you will get default value.

这对我的作品比GSON LIB更好。

This works for me better than GSON lib.

这篇关于Android的JSON解析和转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆