Android 如果没有任何数组,如何解析单个对象
我是android开发领域的新手 如何只解析这个对象Android 如果没有任何数组,如何解析单个对象,android,android-listview,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", "verifica
{
"user_id":21,
"firstname":"",
"lastname":"",
"email":"9654008793",
"isd_code":"91",
"mobile":"9654008793",
"gender":"",
"dob":"0000-00-00",
"image":null,
"status":"0",
"verification_key":"4518"
}
等等你有一个object的数据,所以你需要这样解析:
JsonObject json=new JsonObject();
json=new JsonObject("response");
String userId=json.getString("user_id");
同样,所有其他人都是如此。希望它能帮助您:)
{
表示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");
如果要获取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");
........
JSONObject JSONObject=new JSONObject();
String strUserID=jsonObject.getString(“用户id”);
String strFirstName=jsonObject.getString(“firstname”);
String strLastName=jsonObject.getString(“lastname”);
String strEmail=jsonObject.getString(“电子邮件”);
........
使用谷歌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;
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;
}
publicstaticarraylistgetusersfromjson(stringjson){
//TODO自动生成的方法存根
类型listType=newTypeToken(){}.getType();
ArrayList userList=new Gson().fromJson(json,listType);
返回用户列表;
}
您将获得一系列用户。只需遵循以下教程,这将帮助您它帮助了我……) 在您的项目中,创建一个类文件并将其命名为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);
}
});
}
}
公共类AndroidJSONParsingActivity扩展了ListActivity{
//发出请求的url
专用静态字符串url=”http://api.androidhive.info/contacts/";
//JSON节点名称
专用静态最终字符串标记_CONTACTS=“CONTACTS”;
私有静态最终字符串标记\u ID=“ID”;
私有静态最终字符串标记_NAME=“NAME”;
私有静态最终字符串标记\u EMAIL=“EMAIL”;
私有静态最终字符串标记_ADDRESS=“ADDRESS”;
私有静态最终字符串标记_GENDER=“GENDER”;
专用静态最终字符串标记_PHONE=“PHONE”;
专用静态最终字符串标记\u PHONE\u MOBILE=“MOBILE”;
专用静态最终字符串标记\u PHONE\u HOME=“HOME”;
专用静态最终字符串标记\u PHONE\u OFFICE=“OFFICE”;
//联系JSONArray
JSONArray联系人=null;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//ListView的Hashmap
ArrayList contactList=新建ArrayList();
//创建JSON解析器实例
JSONParser jParser=新的JSONParser();
//从URL获取JSON字符串
JSONObject json=jParser.getJSONFromUrl(url);
试一试{
//获取联系人数组
contacts=json.getJSONArray(TAG_contacts);
//通过所有触点循环
对于(int i=0;ivalue
地图放置(标签标识,标识);
地图放置(标签名称、名称);
地图放置(标签、电子邮件、电子邮件);
地图放置(标签、手机、手机);
//将哈希列表添加到ArrayList
联系人列表。添加(地图);
}
}捕获(JSONException e){
e、 printStackTrace();
}
/**
*将解析的JSON数据更新到ListView中
* */
ListAdapter=新的SimpleAdapter(此,contactList,
R.layout.list_项目,
新字符串[]{TAG\u NAME,TAG\u EMAIL,TAG\u PHONE\u MOBILE},新int[]{
R.id.name、R.id.email、R.id.mobile});
setListAdapter(适配器);
//选择单个ListView项
ListView lv=getListView();
//在选择单个列表项时启动新屏幕
lv.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
//从选定的ListItem获取值
字符串名称=((TextView)view.findviewbyd(R.id.name)).getText().toString();
字符串成本=((TextView)view.findViewById(R.id.email)).getText().toString();
字符串描述=((TextView)view.findviewbyd(R.id.mobile)).getText().toString();
//开始新的意图
Intent in=新的Intent(getApplicationContext(),SingleMenuItemActivity.class);
in.putExtra(标签名称、名称);
in.putExtra(标签、电子邮件、成本);
in.putExtra(标签、手机、说明);
星触觉(in);
}
});
}
}
您也可以查看Gson库@Varun Ajay Gupta您找到解决方案了吗???在提供的链接中提供一些内容。简单地说,放置链接不是回答问题的好方法。这个答案应该修改或删除。@Avadhani Y…我希望现在一切都好了…谢谢您的建议:)
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;
}
}
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);
}
});
}
}