是否可以创建更通用的JSON Parser?
在代码中没有提到任何父节点或子节点标记,我需要解析JSON文件并将其显示在Android Activity中。
此致 迪帕克克里希南
答案 0 :(得分:1)
您可以定义自己的json解析器类 -
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jsonArray = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url, List<NameValuePair> params) {
System.out.println("url:: "+url );
System.out.println("params:: "+ params +" " +params.get(0) );
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
json = sb.toString();
//Log.e("JSON::: ", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
if(!json.equals("null")){
jsonArray = new JSONArray(json);
Log.d("jsonArray:: ", jsonArray+"");
}else{
jsonArray = null;
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jsonArray;
}
}
你的通话类就像 -
public class UserFuctions {
private JSONParser jsonParser;
// constructor
public UserFuctions(){
jsonParser = new JSONParser();
}
private static String HOST_URL = "http://100.43.0.21/pharmacy";
public static final String FS = File.separator;
private static String genericListByNameSearchURL = HOST_URL+FS +"getGenericByName.php";
/**
*
* function make Login Request
* @param email
* @param password
* */
public JSONArray getGenericByName(String genName){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("genName", genName));
JSONArray json = jsonParser.getJSONFromUrl(getGenericByName, params);
return json;
}
}