简体   繁体   English

在Android应用程序中进行JSON解析

[英]JSON parsing in android app

The URL has the following view source.I need to parse and fetch the image path provided for "Folio".can anyone please guide how to get the array of the following paths.thanks in advance 该URL具有以下视图源。我需要解析并获取为“Folio”提供的图像路径。任何人都可以指导如何获取以下路径的数组。提前谢谢

     {"SEO":

  {"Marketing":["http://www.tts.com/media/imagepath/Web.jpg","http://www.tts.com/imagepath/ranks.jpg"],
      "Folio":["http://www.tts.com/media/imagepath/portfolio_images/http_arctictern.t.com.au_folio_portfolio_a_grade_motor_school.html_a_poftfolio_2013_01_11.png",
                                   "http://www.tts.com/media/imagepath/portfolio_images/http_arctictern.t.com.au_folio_portfolio_abc_tarps.html_a_poftfolio_2013_01_10.png",
                                              "http://www.tts.com/media/imagepath/portfolio_images/http_arctictern.t.com.au_folio_portfolio_able_scale.html_a_poftfolio_2013_01_10.png",
                                              "http://www.tts.com/media/imagepath/portfolio_images/http_arctictern.t.com.au_folio_portfolio_accent_aluminum_windows.html_a_poftfolio_2013_01_10.png",
                                              "http://www.tts.com/media/imagepath/portfolio_images/http_arctictern.t.com.au_folio_portfolio_access_health.html_a_poftfolio_2013_01_10.png",
                                              "http://www.tts.com/media/imagepath/portfolio_images/http_arctictern.t.com.au_folio_portfolio_acmeda__zipscreen.html_a_poftfolio_2013_01_11.png",
                                              "http://www.tts.com/media/imagepath/portfolio_images/http_arctictern.t.com.au_folio_portfolio_aditya_birla_minerals.html_a_poftfolio_2013_01_10.png",
                                              "http://www.tts.com/media/imagepath/portfolio_images/http_arctictern.t.com.au_folio_portfolio_advanced_corporate_badges.html_a_poftfolio_2013_01_10.png",
                                              "http://www.tts.com/media/imagepath/portfolio_images/http_arctictern.t.com.au_folio_portfolio_aerotech_fans.html_a_poftfolio_2013_01_10.png",
                                              "http://www.tts.com/media/imagepath/portfolio_images/http_arctictern.t.com.au_folio_portfolio_agriculture_victoria_services_.html_a_poftfolio_2013_01_10.png"]},

 "Services":{"Hosting":["http://www.tts.com/media/imagepath/hostinga.jpg","http://www.tts.com/media/imagepath/hostingb.jpg"],

  "Mobile Apps":["http://www.tts.com/media/imagepath/mobileapp.jpg","http://www.tts.com/media/imagepath/mobilesite.jpg"]

}


}

The JSON parser class contains JSON解析器类包含

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            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 + "\n");
            }
            is.close();
            json = sb.toString();

        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

The main activity contains 主要活动包含

     public class AndroidJSONParsingActivity extends ListActivity {

    private static String url = "http://www.xyz.com/album_pro/array_to_encode";
    private static final String TAG_FOLIO = "SEO";
     JSONArray folio = null;
     @SuppressLint("NewApi")
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
              StrictMode.setThreadPolicy(policy);

            JSONParser jParser = new JSONParser();


            try{

                JSONObject json = jParser.getJSONFromUrl(url);
                Log.v("URL",json.toString());
            JSONObject seo = json.getJSONObject("SEO");
            Log.v("seo",seo.toString());
            JSONArray folio = json.getJSONArray("Folio");

            for(int i=0;i< folio.length();i++)
            {
                Log.v("Test", "test");
            }


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

}
}         

The error iam getting after runnning the app in logcat file is as follows 在logcat文件中运行app后得到的错误如下

03-04 15:36:50.458: W/System.err(23230): org.json.JSONException: No value for Folio
03-04 15:36:50.458: W/System.err(23230):    at org.json.JSONObject.get(JSONObject.java:354)
03-04 15:36:50.458: W/System.err(23230):    at org.json.JSONObject.getJSONArray(JSONObject.java:544)
03-04 15:36:50.458: W/System.err(23230):    at com.example.testgallery.AndroidJSONParsingActivity.onCreate(AndroidJSONParsingActivity.java:37)
03-04 15:36:50.458: W/System.err(23230):    at android.app.Activity.performCreate(Activity.java:5008)
03-04 15:36:50.458: W/System.err(23230):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
03-04 15:36:50.458: W/System.err(23230):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)

Firstly create an ArrayList like... 首先创建一个像ArrayList一样的...

ArrayList<String> urlList = new ArrayList<String>();

Get Folio JSONArray from JSONObject Marketing like... 从JSONObject Marketing获取Folio JSONArray,如...

JSONArray folio = marketing.getJSONArray("Folio");

Now put all items from folio to urlList like... 现在把所有项目从作品集放到urlList就像......

for(int i=0;i<folio.length();i++){
  urlList.add(folio.getString(i));
}

Now you can use this urlList. 现在您可以使用此urlList。

Try this 尝试这个

JSONObject json = jParser.getJSONFromUrl(url);
JSONObject seoObj = jObj.getJSONObject("SEO");
JSONArray folioArr = seoObj.getJSONArray("Folio");
ArrayList<String> image_urls = new ArrayList<String>();
for (int i = 0; i < folioArr.length(); i++) {
image_urls.add(folioArr.getString(i));
}

Assume you have this JSON in a String variable called stringSource . 假设您在名为stringSourceString变量中有此JSON。

JSONObject json = new JSONObject(stringSource);
JSONObject seo = json.getJSONObject("SEO");
JSONArray folio = json.getJSONArray("Folio");

Then use JSONArray.getString(int index) to retrieve each URL from array. 然后使用JSONArray.getString(int index)从数组中检索每个URL。

Convert your Response to String 将响应转换为String

Then 然后

JSONObject json = new JSONObject(response.toString());
//Since Folio is an array
JSONArray folio = json.getJSONArray("Folio");
//Get Individual Links
for(int i=0;i<folio.length();i++){
   //Fetch Your Code Here
   String image = folio.getString(i);

}

NB: I think you got an invalid JSON response . 注意:我认为你的JSON响应无效。 I checked your response here 在这里检查了你的回复

Take this class 上这堂课吧

    public class GettingResponseFromUrl {

    public static String convertStreamToString(InputStream inputStream)
            throws IOException {
        if (inputStream != null) {
            StringBuilder sb = new StringBuilder();
            String line;
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                inputStream.close();
            }
            return sb.toString();
        } else {
            return "";
        }
    }

    public static String GetDataFromServer(String url, String method) {
        url = url.replace(" ", "%20");
        String Root_Response = null;
        try {
            HttpParams basicparams = new BasicHttpParams();
            int timeoutConnection = 120000;
            HttpConnectionParams.setConnectionTimeout(basicparams,
                    timeoutConnection);
            DefaultHttpClient client = new DefaultHttpClient(basicparams);
            URI uri = new URI(url);
            HttpResponse res = null;
            if (method.equalsIgnoreCase("POST")) {
                HttpPost httpPost = new HttpPost(uri);
                res = client.execute(httpPost);
            } else if (method.equalsIgnoreCase("GET")) {
                HttpGet httpGet = new HttpGet(uri);
                res = client.execute(httpGet);
            }
            InputStream data = res.getEntity().getContent();
            Root_Response = convertStreamToString(data);

        } catch (ClientProtocolException e) {
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return Root_Response;
    }

}

//than call web service from below code //比从下面的代码调用web服务

new GettingData().execute();

    private class GettingData extends AsyncTask<String, String, String> {

        private ProgressDialog progressDialog;
            private String response;

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
            progressDialog = new ProgressDialog(mContext);
            progressDialog.setMessage("Loading ...");
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(true);
            progressDialog.show();

        }

        @Override
        protected String doInBackground(String... args) {
try {
            Response = GettingResponseFromUrl
                    .GetDataFromServer(URL, "POST");
            Log.e("Response", Response);
        } catch (Exception e) {
        }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {


                }
            });
            return null;
        }

        @Override
        protected void onPostExecute(String args) {
            progressDialog.dismiss();

        }
    }

Check out this tool which is freely available 看看这个免费提供的工具

Android Class Creator tool Android类创建工具

It's tutorial is with it. 它的教程就是它。 It's so easy to use. 它很容易使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM