1. 程式人生 > >將json串轉化為字串

將json串轉化為字串

  1. 將json文件轉化為字串

    StringBuilder sb=null;
    try {
        //獲取檔案輸入流
        InputStream input = getAssets().open(fileName);
        //快取輸入流
        BufferedReader br=new BufferedReader(new InputStreamReader(input));
         //定義的自定義儲存資料庫
        sb = new StringBuilder();
        //臨時儲存字串
        String con;
        //迴圈獲取輸入流中的資料
        while((con=br.readLine())!=null){
            //將資料存在儲存器中
            sb.append(con);
        }
    
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //返回儲存器中的字串
    return sb.toString();
    
  2. 將網路請求的json流轉化為字串的工具類
    //需要傳過來一個輸入流和編碼格式


import android.os.AsyncTask;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 使用AsyncTask+HttpURLConnection請求資料
 * Created by e531 on 2017/10/12.
 */
public class
MyTask extends AsyncTask<String,Void,String> {
//申請一個介面類物件 private Icallbacks icallbacks; //將無參構造設定成私有的,使之在外部不能夠呼叫 private MyTask(){} //定義有參構造方法 public MyTask(Icallbacks icallbacks) { this.icallbacks = icallbacks; } @Override protected String doInBackground(String... params) { String str=""
; try { //使用HttpUrlConnection URL url=new URL(params[0]); HttpURLConnection connection=(HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); if(connection.getResponseCode()==200){ InputStream inputStream=connection.getInputStream(); //呼叫工具類中的靜態方法 str=StreamToString.streamToStr(inputStream,"utf-8"); } } catch (MalformedURLException e) { e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } return str; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); //解析,封裝到bean,更新ui元件 icallbacks.updateUiByjson(s); } //定義一個介面 public interface Icallbacks{ /** * 根據回傳的json字串,解析並更新頁面元件 * @param jsonstr */ void updateUiByjson(String jsonstr); } }

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by e531 on 2017/10/12.
 */
public class StreamToString {

    public static String streamToStr(InputStream inputStream,String chartSet){

        StringBuilder builder=new StringBuilder();
        try {
            BufferedReader br=new BufferedReader(new InputStreamReader(inputStream,chartSet));
            String con;
            while ((con=br.readLine())!=null){
                builder.append(con);
            }

            br.close();
            return builder.toString();


        } catch (Exception e) {
            e.printStackTrace();
        }


        return "";
    }
}