如何解析没有任何数组只是一个对象

时间:2013-06-25 10:24:11

标签: android android-listview

我是Android开发领域的新手。

如何解析这个对象。

{
    "user_id":21,
    "firstname":"",
    "lastname":"",
    "email":"9654008793",
    "isd_code":"91",
    "mobile":"9654008793",
    "gender":"",
    "dob":"0000-00-00",
    "image":null,
    "status":"0",
    "verification_key":"4518"
}

6 个答案:

答案 0 :(得分:0)

JSONObject obj = new JSONObject(yourString);
int userId = obj.getInt("user_id");
String firstname = obj.getString("firstname");

等等

答案 1 :(得分:0)

你有一个对象的数据,所以你需要像这样解析:

JsonObject json=new JsonObject();
json=new JsonObject("response");
String userId=json.getString("user_id");
同样地,所有其他人。希望它可以帮助你:)

答案 2 :(得分:0)

{表示JSONObject节点。

    JSONObject jsono = new JSONObject(mystring);

    String id = jsono.getString("user_id");
    //String firstname = jsono.getString("firstname");
    //String lastname =  jsono.getString("lastname");
    String email = jsono.getString("email");
    String isdcode = jsono.getString("isd_code");
    String mobile = jsono.getString("mobile");
    //String gender = jsono.getString("gender");
    String dob = jsono.getString("dob");
    //String image= jsono.getString("image");
    String status= jsono.getString("status");
    String key= jsono.getString("verification_key"); 

答案 3 :(得分:0)

如果你想在JSON中获取每个对象,请按以下步骤操作:

JSONObject jsonObject = new JSONObject(<Your String Here>);
String strUserID = jsonObject.getString("user_id");
String strFirstName = jsonObject.getString("firstname");
String strLastName = jsonObject.getString("lastname");
String strEmail = jsonObject.getString("email");
........

答案 4 :(得分:0)

使用google-gson库,它非常易于使用。

您可以在这里找到图书馆:

https://code.google.com/p/google-gson/

只需创建一个与json具有相同字段的对象(确保类型是您正在接收的类型(string,int,double等等)):

public class User {
    private int user_id;
    private String firstname;
    private String lastname;
    private String email;
    private int mobile;
    private int isd_code;
    private String gender;
    private String dob;
    private String image;
    private int status;
    private int verification_key;
}

然后将此功能添加到类User ...

public class User {
    private int user_id;
    private String firstname;
    private String lastname;
    private String email;
    private int mobile;
    private int isd_code;
    private String gender;
    private String dob;
    private String image;
    private int status;
    private int verification_key;


    public static User getUserFromJson(String json) {

        return new Gson().fromJson(json, User.class);
    }
}

json String是你的json和Voila!你正在返回一个java用户对象,其中包含json的信息。

如果您在json上收到一组用户....

public static ArrayList<User> getUsersFromJson(String json) {
    // TODO Auto-generated method stub
    Type listType = new TypeToken<ArrayList<User>>() {}.getType();
    ArrayList<User> userList = new Gson().fromJson(json, listType);
    return userList;
}

你得到了一系列用户。

答案 5 :(得分:0)

只需按照以下教程,这将帮助您帮助我...... :)

http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

在您的项目中创建一个类文件并将其命名为JSONParser.java。解析器类有一个方法,它将使http请求获取JSON数据并返回一个JSONObject。

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();          

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

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

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

解析JSON数据并更新到ListView

public class AndroidJSONParsingActivity extends ListActivity {

// url to make request
private static String url = "http://api.androidhive.info/contacts/";

// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";

// contacts JSONArray
JSONArray contacts = null;

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

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);

    try {
        // Getting Array of Contacts
        contacts = json.getJSONArray(TAG_CONTACTS);

        // looping through All Contacts
        for(int i = 0; i < contacts.length(); i++){
            JSONObject c = contacts.getJSONObject(i);

            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String email = c.getString(TAG_EMAIL);
            String address = c.getString(TAG_ADDRESS);
            String gender = c.getString(TAG_GENDER);

            // Phone number is agin JSON Object
            JSONObject phone = c.getJSONObject(TAG_PHONE);
            String mobile = phone.getString(TAG_PHONE_MOBILE);
            String home = phone.getString(TAG_PHONE_HOME);
            String office = phone.getString(TAG_PHONE_OFFICE);

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_ID, id);
            map.put(TAG_NAME, name);
            map.put(TAG_EMAIL, email);
            map.put(TAG_PHONE_MOBILE, mobile);

            // adding HashList to ArrayList
            contactList.add(map);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }


    /**
     * Updating parsed JSON data into ListView
     * */
    ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.list_item,
            new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
                    R.id.name, R.id.email, R.id.mobile });

    setListAdapter(adapter);

    // selecting single ListView item
    ListView lv = getListView();

    // Launching new screen on Selecting Single ListItem
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
            String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
            String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
            in.putExtra(TAG_NAME, name);
            in.putExtra(TAG_EMAIL, cost);
            in.putExtra(TAG_PHONE_MOBILE, description);
            startActivity(in);
        }
    });
}

}