JSON服务器的使用和客户端的解析

来源:互联网 发布:centos企业邮箱搭建 编辑:程序博客网 时间:2024/06/01 10:21

服务器端的使用:

String jsonString="";String action_flag=request.getParameter("action_flag");if(action_flag=request.getParameter("action_flag"));{    jsonString=JsonTools.createJsonString("person",service.getPersin);//通过使用JsonTools工具类把数据封装成String串}

客户端Json数据的解析
写一个HttpUtils工具类

public  static String getJsonContent(String url_path){        try{    URL url=new URL(url_path); HttpURLConnection connection=(HttpURlConnection)url.openConnection();connection.setConnectTimeout(3000);connection.setRequestMethod("GET");connection.setDoInput(true);int code=connection.getResponseCode();if(code==200){    return changeInputStream(InputStream inputStream);;}}} public static String changeInputStream(InputStream inputStream){    String jsonString="";ByteArrayOutPutStream outputStream=new ByteArrayoutPutStream(); int len=0;    byte[] data=new byte[1024];try{    while((len=InputStream.read(data))!=0){    outputStream.write(data,0,len);}jsonString=new String(outputStream.toByteArray());}}

通过使用JsonObject类或者是JsonArray来解析Json字符串

public class JsonTools{    public static Person getPerson(String key,String jsonString){    try{    JSONObject jsonObject=new JSONObject(jsonString);    JSONObject personObject=jsonObject.getJSONObject("person");    person.setname(personObject.getString("name"));}}}
0 0
原创粉丝点击