怎么解析从服务器返回的json

怎么解析从服务器返回的json,第1张

json数据格式解析我自己分为两种;

一种是普通的,一种是带有数组形式的;

普通形式的:

服务器端返回的json数据格式如下:

复制代码代码如下:

{"userbean":{"Uid":"100196","Showname":"\u75af\u72c2\u7684\u7334\u5b50","Avtar":null,"State":1}}

分析代码如下:

复制代码代码如下:

// TODO 状态处理 500 200

int res = 0

res = httpClient.execute(httpPost).getStatusLine().getStatusCode()

if (res == 200) {

/*

* 当返回码为200时,做处理

* 得到服务器端返回json数据,并做处理

* */

HttpResponse httpResponse = httpClient.execute(httpPost)

StringBuilder builder = new StringBuilder()

BufferedReader bufferedReader2 = new BufferedReader(

new InputStreamReader(httpResponse.getEntity().getContent()))

String str2 = ""

for (String s = bufferedReader2.readLine()s != nulls = bufferedReader2

.readLine()) {

builder.append(s)

}

Log.i("cat", ">>>>>>" + builder.toString())

JSONObject jsonObject = new JSONObject(builder.toString())

.getJSONObject("userbean")

String Uid

String Showname

String Avtar

String State

Uid = jsonObject.getString("Uid")

Showname = jsonObject.getString("Showname")

Avtar = jsonObject.getString("Avtar")

State = jsonObject.getString("State")

带数组形式的:

服务器端返回的数据格式为:

复制代码代码如下:

{"calendar":

{"calendarlist":

[

{"calendar_id":"1705","title":"(\u4eb2\u5b50)ddssd","category_name":"\u9ed8\u8ba4\u5206\u7c7b","showtime":"1288927800","endshowtime":"1288931400","allDay":false},

{"calendar_id":"1706","title":"(\u65c5\u884c)","category_name":"\u9ed8\u8ba4\u5206\u7c7b","showtime":"1288933200","endshowtime":"1288936800","allDay":false}

]

}

}

分析代码如下:

复制代码代码如下:

// TODO 状态处理 500 200

int res = 0

res = httpClient.execute(httpPost).getStatusLine().getStatusCode()

if (res == 200) {

/*

* 当返回码为200时,做处理

* 得到服务器端返回json数据,并做处理

* */

HttpResponse httpResponse = httpClient.execute(httpPost)

StringBuilder builder = new StringBuilder()

BufferedReader bufferedReader2 = new BufferedReader(

new InputStreamReader(httpResponse.getEntity().getContent()))

String str2 = ""

for (String s = bufferedReader2.readLine()s != nulls = bufferedReader2

.readLine()) {

builder.append(s)

}

Log.i("cat", ">>>>>>" + builder.toString())

/**

* 这里需要分析服务器回传的json格式数据,

*/

JSONObject jsonObject = new JSONObject(builder.toString())

.getJSONObject("calendar")

JSONArray jsonArray = jsonObject.getJSONArray("calendarlist")

for(int i=0i<jsonArray.length()i++){

JSONObject jsonObject2 = (JSONObject)jsonArray.opt(i)

CalendarInfo calendarInfo = new CalendarInfo()

calendarInfo.setCalendar_id(jsonObject2.getString("calendar_id"))

calendarInfo.setTitle(jsonObject2.getString("title"))

calendarInfo.setCategory_name(jsonObject2.getString("category_name"))

calendarInfo.setShowtime(jsonObject2.getString("showtime"))

calendarInfo.setEndtime(jsonObject2.getString("endshowtime"))

calendarInfo.setAllDay(jsonObject2.getBoolean("allDay"))

calendarInfos.add(calendarInfo)

}

总结,普通形式的只需用JSONObject ,带数组形式的需要使用JSONArray 将其变成一个list。

json数组用js解析并显示的方法:

假如后台返回的数据是:

{'id':1,'name':'st','grant':[{'tm_id':1,'tm_name':'zc'},{'tm_id':2,'tm_name':'ww'}]}

前台获取:

var data = eval_r("(" + json + ")")//json为接收的后台返回的数据;

var id1 = data.grant[0].tm_id

var name1 = data.grant[0].tm_name

var id2 = data.grant[1].tm_id

var name2 = data.grant[1].tm_name

循环读取:

for(var i=0i<data.grant.lengthi++){

alert(data.grant[i].tm_id+"---"+data.grant[i].tm_name)

}

在对应表格中显示即可。

因为这次要从服务器端得到Json数据,并且通过解析之后把解析后的数据显示在Android客户端中,首先部署服务器端代码(直接使用Jsp/Servlet):

构造的Json数据如下:

[{"name":"张三","address":"北京","age":20},{"name":"李四","address":"上海","age":30},{"name":"王五","address":"深圳","age":35}]

[一]服务器端(Person.java省略):

①:数据构造JsonService.java

public class JsonService {

public static List<Person>getListPerson() {

List<Person>mLists = new ArrayList<Person>()

mLists.add(new Person("张三", "北京", 20))

mLists.add(new Person("李四", "上海", 30))

mLists.add(new Person("王五", "深圳", 35))

return mLists

}

②:Servlet的代码(包括构造Json数据,没有使用Json数据转换方法)JsonServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html")

response.setCharacterEncoding("UTF-8")

PrintWriter out = response.getWriter()

List<Person>persons = JsonService.getListPerson()

StringBuffer sb = new StringBuffer()

sb.append('[')

for (Person person : persons) {

sb.append('{').append("\"name\":").append("\""+person.getName()+"\"").append(",") sb.append("\"address\":").append("\""+person.getAddress()+"\"").append(",")

sb.append("\"age\":").append(person.getAge())

sb.append('}').append(",")

}

sb.deleteCharAt(sb.length() - 1)

sb.append(']')

out.write(new String(sb))

out.flush()

out.close()

}

③:部署到Tomact 浏览器输入http://localhost/JsonWeb/JsonServlet直接访问结果如下:

[{"name":"张三","address":"北京","age":20},{"name":"李四","address":"上海","age":30},{"name":"王五","address":"深圳","age":35}]

至此服务器端代码编码完成,下面进行客户端代码编写 (二)客户端(Person类,和展示数据的布局文件因为简单省去) ①:获取服务器端的Json数据并且解析的工具类JsonParse.java 必要的需要导入的包省去

public class JsonParse {

/**

* 解析Json数据

*

* @param urlPath

* @return mlists

* @throws Exception

*/

public static List<Person>getListPerson(String urlPath) throws Exception {

List<Person>mlists = new ArrayList<Person>()

byte[] data = readParse(urlPath)

JSONArray array = new JSONArray(new String(data))

for (int i = 0i <array.length()i++) {

JSONObject item = array.getJSONObject(i)

String name = item.getString("name")

String address = item.getString("address")

int age = item.getInt("age")

mlists.add(new Person(name, address, age))

}

return mlists

}

/**

* 从指定的url中获取字节数组

*

* @param urlPath

* @return 字节数组

* @throws Exception

*/

public static byte[] readParse(String urlPath) throws Exception {

ByteArrayOutputStream outStream = new ByteArrayOutputStream()

byte[] data = new byte[1024]

int len = 0

URL url = new URL(urlPath)

HttpURLConnection conn = (HttpURLConnection) url.openConnection()

InputStream inStream = conn.getInputStream()

while ((len = inStream.read(data)) != -1) {

outStream.write(data, 0, len)

}

inStream.close()

return outStream.toByteArray()

}

}

②:主Activity类

public class MainActivity extends Activity {

private Button mButton

private ListView mListView

//使用IP不能使用localhost或者127.0.0.1,因为android模拟器默认绑定这个IP,这里应该访问局域网IP

private static final String urlPath = "http://10.16.31.207/JsonWeb/JsonServlet"

private static final String TAG = "MainActivity"

private List<Person>persons

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState)

setContentView(R.layout.main)

mButton = (Button) findViewById(R.id.button1)

mListView = (ListView) findViewById(R.id.listView1)

mButton.setOnClickListener(new MyOnClickListener())

}

private class MyOnClickListener implements OnClickListener {

@Override

public void onClick(View v) {

try {

// 得到Json解析成功之后数据

persons = JsonParse.getListPerson(urlPath)

List<HashMap<String, Object>>data = new ArrayList<HashMap<String, Object>>()

for (int i = 0i <persons.size()i++) {

HashMap<String, Object>map = new HashMap<String, Object>()

map.put("name", persons.get(i).getName())

map.put("address", persons.get(i).getAddress())

map.put("age", persons.get(i).getAge())

data.add(map)

}

//初始化适配器,并且绑定数据

SimpleAdapter _Adapter = new SimpleAdapter(MainActivity.this,

data, R.layout.listview_item, new String[] { "name",

"address", "age" }, new int[] { R.id.textView1,

R.id.textView2, R.id.textView3 })

mListView.setAdapter(_Adapter)

} catch (Exception e) {

Toast.makeText(MainActivity.this, "解析失败", 2000).show()

Log.i(TAG, e.toString())

}

}

}


欢迎分享,转载请注明来源:夏雨云

原文地址:https://www.xiayuyun.com/zonghe/268460.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-18
下一篇2023-04-18

发表评论

登录后才能评论

评论列表(0条)

    保存