Android 解析json问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 解析json问题相关的知识,希望对你有一定的参考价值。
一、 编写说明
本接口支持数据交换格式为Json。服务器端返回数据均为json格式,手机端使用Json工具解析数据。
所有的返回值均改为map json
二、 接口描述
1. 登入
1) 功能描述
登入系统,注册session。
2) 方法名称
validate ();
3) 输入
String loginId
String password
4) 输出
返回map json数据
[success= , //是否登入成功
JSESSIONID= , //sessionid
loginName= ,//姓名
orgname= ,//单位名称]
5) 访问地址
/loginbyandroid/validate.do
给我的接口文档如上,我怎么通过方法validate ();得到输出的json串呢?还有就是访问地址该怎么用?
求教大神解答,满意会加分50的
1、首先,搭建一个服务器的工程:JsonProject这个项目
源代码:
Person.java
package com.json.domain;
public class Person
private int id;
private String name;
private String address;
public Person()
super();
public Person(int id, String name, String addrss)
super();
this.id = id;
this.name = name;
this.address = addrss;
public int getId()
return id;
public void setId(int id)
this.id = id;
public String getName()
return name;
public void setName(String name)
this.name = name;
public String getAddress()
return address;
public void setAddress(String address)
this.address = address;
@Override
public String toString()
return "Person [addrss=" + address + ", id=" + id + ", name=" + name
+ "]";
JsonService.java
package com.json.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.json.domain.Person;
public class JsonService
public JsonService()
public Person getPerson()
Person person = new Person(1001,"jack","上海黄浦区");
return person;
public List<Person> getListPerson()
List<Person> list = new ArrayList<Person>();
Person person1 = new Person(1001,"jack","上海黄浦区");
Person person2 = new Person(1002,"rose","上海闵行区");
Person person3 = new Person(1003,"mick","上海黄浦区");
list.add(person1);
list.add(person2);
list.add(person3);
return list;
public List<String> getListString()
List<String> list = new ArrayList<String>();
list.add("北京");
list.add("上海");
list.add("湖南");
return list;
public List<Map<String,Object>> getListMaps()
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
Map<String,Object> map1 = new HashMap<String, Object>();
Map<String,Object> map2 = new HashMap<String, Object>();
map1.put("id", 1001);
map1.put("name", "jack");
map1.put("address", "北京");
map2.put("id", 1001);
map2.put("name", "rose");
map2.put("address", "上海");
list.add(map1);
list.add(map2);
return list;
JsonServlet.java
package com.json.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.json.service.JsonService;
import com.json.tools.JsonTools;
public class JsonServlet extends HttpServlet
private JsonService service;
/**
* Constructor of the object.
*/
public JsonServlet()
super();
/**
* Destruction of the servlet. <br>
*/
public void destroy()
super.destroy(); // Just puts "destroy" string in log
// Put your code here
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
this.doPost(request, response);
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String jsonString = "";
String action_flag = request.getParameter("action_flag");
if(action_flag.equals("person"))
jsonString = JsonTools.createJsonString("person", service.getPerson());
else if(action_flag.equals("persons"))
jsonString = JsonTools.createJsonString("persons", service.getListPerson());
else if(action_flag.equals("listString"))
jsonString = JsonTools.createJsonString("listString", service.getListString());
else if(action_flag.equals("listMap"))
jsonString = JsonTools.createJsonString("listMap", service.getListMaps());
out.println(jsonString);
out.flush();
out.close();
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException
service = new JsonService();
2、通过浏览器
访问地址一:http://wulianghuan-pc:8080/JsonProject/servlet/JsonServlet?action_flag=person
输出以下结果:
"person":"address":"上海黄浦区","id":1001,"name":"jack"
访问地址二:http://wulianghuan-pc:8080/JsonProject/servlet/JsonServlet?action_flag=persons
输出以下结果:
"persons":["address":"上海黄浦区","id":1001,"name":"jack","addrss":"上海闵行区","id":1002,"name":"rose","address":"上海黄浦区","id":1003,"name":"mick"]
访问地址三:http://wulianghuan-pc:8080/JsonProject/servlet/JsonServlet?action_flag=listString
输出以下结果:
"persons":["北京","上海","湖南"]
访问地址四:http://wulianghuan-pc:8080/JsonProject/servlet/JsonServlet?action_flag=listMap
输出以下结果:
"persons":["id":1001,"address":"北京","name":"jack","id":1001,"address":"上海","name":"rose"] 参考技术A // / http地址
String httpUrl = ip + ":" + 端口号 + "/loginbyandroid/validate.do";
// HttpPost连接对象
HttpPost httpRequest = new HttpPost(httpUrl);
// 使用NameValuePair来保存要传递的Post参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
// 添加要传递的参数
params.add(new BasicNameValuePair("loginId", "value"));
params.add(new BasicNameValuePair("password", "value"));
// 设置字符集
HttpEntity httpentity;
try
httpentity = new UrlEncodedFormEntity(params, "utf-8");
// 请求httpRequest
httpRequest.setEntity(httpentity);
// 取得默认的HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 取得HttpResponse
HttpResponse httpResponse;
httpResponse = httpclient.execute(httpRequest);
// HttpStatus.SC_OK表示连接成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
// 取得返回的字符串
String strResult = EntityUtils.toString(httpResponse
.getEntity());
JSONArray jsonArray = new JSONArray(strResult);
for (int i = 0; i < jsonArray.length(); i++)
JSONObject jsonObject = (JSONObject) jsonArray.opt(i);
String success = jsonObject.getString("success");
String JSESSIONID = jsonObject.getString("JSESSIONID");
String loginName = jsonObject.getString("loginName");
String orgname = jsonObject.getString("orgname");
System.out.println(" success = " + success
+ " JSESSIONID = " + JSESSIONID + " loginName = "
+ loginName + " orgname = " + orgname);
else
System.out.println("请求错误!");
catch (ClientProtocolException e)
e.printStackTrace();
catch (IOException e)
e.printStackTrace();
追问
你这是直接调用URL得到一个json串然后在解析的吧,,我得是通过接口中的一个方法validate()来获得json串,然后在解析该json串。这个方法我该怎么调用呢呢
追答接口的地址就是validate()方法啊,也就是说/loginbyandroid/validate.do指的就是validate()方法
本回答被提问者采纳 参考技术B 换成这样格式就对了:'T1': [
'BU_ID': '63',
'BU_NAME': 'testBU'
,
'BU_ID': '61',
'BU_NAME': 'Sunford'
,
'BU_ID': '62',
'BU_NAME': 'ZXHTsss'
,
'BU_ID': '42',
'BU_NAME': 'Conti1'
,
'BU_ID': '43',
'BU_NAME': 'NewBU'
]
以上回答你满意么?追问
不是那意思,我问的是:我怎么通过方法validate ();得到输出的json串呢?还有就是访问地址该怎么用?
就是代码该怎么写 用JSONObject该怎么用
你看看返回的字符串里面是否有city的数据 参考技术D http://blog.csdn.net/u012975370/article/details/46981823
改造解析JSON响应空值Android
【中文标题】改造解析JSON响应空值Android【英文标题】:Retrofit parsing JSON response null values Android 【发布时间】:2015-08-18 07:31:55 【问题描述】:您好,我无法弄清楚为什么我的回复得到空值。我在 Android 上使用 Retrofit 库。
原始 json
"images": [
"image":
"name": "nike adver",
"url": "http:\/\/wallpaperbarcelona.com\/wp-content\/uploads\/2013\/07\/neymar-nike-advert.jpg",
"type": "photo"
]
// 接口
public interface PromoImagesAPI
@GET("/FriendsCMS/images/?type=photo&format=json")
void promoImages(Callback<ImagesObject> callback);
请求函数
private void requestNewsData(String uri)
RestAdapter api = new RestAdapter.Builder().setEndpoint(ENDPOINT).build();
PromoImagesAPI restapi = api.create(PromoImagesAPI.class);
restapi.promoImages(new Callback<Images>()
@Override
public void success(Images imageObjects, Response response)
System.out.println("webservice " +response.getUrl());
for (int i = 0; i < imageObjects.images.size(); i++)
System.out.println("webservice " +imageObjects.getImages().get(i).getUrl());
@Override
public void failure(RetrofitError error)
System.out.println("webservice " + error);
);
波乔
public class ImagesObject
public List<Images> images;
public class Images
public String name;
public String url;
public String type;
public String getName()
return name;
public String getUrl()
return url;
public String getType()
return type;
public void setName(String name)
this.name = name;
public void setUrl(String url)
this.url = url;
public void setType(String type)
this.type = type;
问题是for循环中的元素数量是正确的,我已经测试过,值都是空的。我错过了什么,任何帮助将不胜感激。谢谢
【问题讨论】:
【参考方案1】:使用http://www.jsonschema2pojo.org/创建你的java对象模型并执行以下调用
public interface PromoImagesAPI
@GET("/FriendsCMS/images/?type=photo&format=json")
void promoImages(Callback<Images> callback);
【讨论】:
感谢您的回答,但我仍然返回空值。 很抱歉还是 null :- ( 您好,我已经使用了您上传的 pojo 和相同的 api 调用来更新 rquest 函数 尝试将ImagesObject改为Image 让我们continue this discussion in chat.【参考方案2】:是的,我同意。我也错过了@Expose 注释。当使用第三方工具从json
转换为kotlin
或java
类时,可能会特别发生这种情况。在进行单元测试时,我还使用 Gson 从 json
转换,一切都顺利通过,直到我运行应用程序并且一切都返回空值
【讨论】:
以上是关于Android 解析json问题的主要内容,如果未能解决你的问题,请参考以下文章