2022年7月31日

Android 字串轉Json

 


import android.app.Activity;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;


public class Json_loader {



private Activity p_activity;
public Json_loader(Activity activity){

p_activity=activity;


}

public JSONObject string_to_json(String json_str){

JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json_str);
}catch (Exception e){

}
return jsonObject;

}

public JSONObject load_from_raw(int id){


//EX. R.raw.test
InputStream is = p_activity.getResources().openRawResource(id);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String json_str="";
try {
String line = reader.readLine();
while (line != null) {
json_str+=line+"\n";
line = reader.readLine();
}
reader.close();
}catch (Exception e){

}
return string_to_json(json_str);

}



}

沒有留言:

張貼留言