0

我是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"
}
4

6 回答 6

0

使用 google-gson 库,超级好用。

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

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

只需创建一个与您的 json 具有相同字段的对象(确保类型是您正在接收的类型(字符串、整数、双精度等)):

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字符串在哪里是你的json,瞧!您正在返回一个 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;
}

你得到了一组用户。

于 2013-06-25T10:53:01.757 回答
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);
        }
    });
}

}
于 2013-06-25T11:41:08.607 回答
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"); 
于 2013-06-25T10:29:01.707 回答
0
JSONObject obj = new JSONObject(yourString);
int userId = obj.getInt("user_id");
String firstname = obj.getString("firstname");

等等

于 2013-06-25T10:25:30.587 回答
0

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

JsonObject json=new JsonObject();
json=new JsonObject("response");
String userId=json.getString("user_id");

同样,所有其他人。希望对你有帮助:)

于 2013-06-25T10:27:17.030 回答
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");
........
于 2013-06-25T10:31:57.483 回答