如何在android json解析中消除对象内的空字符串

时间:2014-05-05 07:54:41

标签: android json parsing

嗨朋友们,我喜欢从url解析json,也喜欢对null值字段进行elimate,只显示有价值的对象,如果有任何已知的语法,请提前指导我。

  

JSON结构

{
    "daftar_rs": [
        {
            "Name": "exe1",
            "URL": "http://samir-mangroliya.blogspot.in/p/android-json-parsing-tutorial.html"
        },
        {
            "Name": "exe2",
            "URL": "https://code.google.com/p/json-io/"
        },
        {
            "Name": "exe3",
            "URL": ""
        },
        {
            "Name": "exe4",
            "URL": "http://stackoverflow.com/questions/10964203/android-removing-jsonobject"
        },
        {
            "Name": "exe5",
            "URL": ""
        },
        {
            "Name": "exe6",
            "URL": ""
        }
    ],
    "success": 1
}
  

MainActivity

public class MainActivity extends Activity {

    ListView lv;
    List<String> titleCollection = new ArrayList<String>();
    List<String> urlCollection = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView) findViewById(R.id.listView1);

        // we will using AsyncTask during parsing 
        new AsyncTaskParseJson().execute();
        lv.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                  String linkUrl = urlCollection.get(arg2);
                   Intent webViewIntent = new Intent(MainActivity.this, WebViewActivity.class);
                   webViewIntent.putExtra("url", linkUrl);
                   startActivity(webViewIntent);

            }
    });
    }

    public void loadContents() 
    {
     ArrayAdapter<String> adapter =new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,titleCollection);
     lv.setAdapter(adapter);
    }

    // you can make this class as another java file so it will be separated from your main activity.
    public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

        final String TAG = "AsyncTaskParseJson.java";

        // set your json string url here

        String yourJsonStringUrl = "http://192.168.1.167/vinandrophp/vinex.php";

        // contacts JSONArray
        JSONArray dataJsonArr = null;

        @Override
        protected void onPreExecute() {}

        @Override
        protected String doInBackground(String... arg0) {

            try {

                // instantiate our json parser
                JsonParser jParser = new JsonParser();

                // get json string from url
                JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);


                // loop through all users
                for (int i = 0; i < dataJsonArr.length(); i++) {

                    JSONObject c = dataJsonArr.getJSONObject(i);

                    // Storing each json item in variable

                    titleCollection.add(c.getString("Name"));
                    urlCollection.add(c.getString("URL"));


                    // show the values in our logcat
                    Log.e(TAG, "Name: " + titleCollection 
                            + ", URL: " + urlCollection);

                }

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

            return null;
        }

        @Override
        protected void onPostExecute(String strFromDoInBg) {
             loadContents();

        }
    }
}

JsonParser.java

    public class JsonParser {

        final String TAG = "JsonParser.java";

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

        public JSONObject getJSONFromUrl(String url) {

            // make HTTP request
            try {

                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(TAG, "Error converting result " + e.toString());
            }

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

            // return JSON String
            return jObj;
        }
    }

5 个答案:

答案 0 :(得分:1)

只需在代码中查看。

String linkUrl = urlCollection.get(arg2);

if (linkUrl== null || linkUrl.equals("")){
    // null
}
else{ 
    // not null so put to extras and start intent
    Intent webViewIntent = new Intent(MainActivity.this, WebViewActivity.class);
    webViewIntent.putExtra("url", linkUrl);
    startActivity(webViewIntent);
}

答案 1 :(得分:1)

尝试以下代码

for (int i = 0; i < dataJsonArr.length(); i++) 
{
    JSONObject c = dataJsonArr.getJSONObject(i);
    // Storing each json item in variable

    String Name = c.getString("Name"); 
    String Url = c.getString("URL")

    if(!TextUtils.isEmpty(Name) && !TextUtil.isEmpty(Url)) 
    {
        titleCollection.add(Name);
        urlCollection.add(Url)); 
    }

    // show the values in our logcat
    Log.e(TAG, "Name: " + titleCollection + ", URL: " + urlCollection);
}

答案 2 :(得分:0)

尝试以下代码: -

if(c.getString("URL").equals("") || c.isNULL("URL"))
{
     // do nothing
}
else
{
     titleCollection.add(c.getString("Name"));
     urlCollection.add(c.getString("URL"));
}

答案 3 :(得分:0)

将循环更改为

       for (int i = 0; i < dataJsonArr.length(); i++) {

                JSONObject c = dataJsonArr.getJSONObject(i);

                // Storing each json item in variable
                String name = c.getString("Name");
                String url = c.getString("URL");
                if(name != null && !(name.equals("")) 
                          && url != null && !(url.equals(""){
                     titleCollection.add(c.getString("Name"));
                     urlCollection.add(c.getString("URL"));                
                }



                // show the values in our logcat
                Log.e(TAG, "Name: " + titleCollection 
                        + ", URL: " + urlCollection);

            }

答案 4 :(得分:0)

如果JsonParser类中的键为空,请尝试使用正则表达式替换键和值。

json=json.replaceAll("\\n",""); //you should do not have any new lines after commas
json=json.replaceAll(",\\W*\"\\w+\":\\W?(\"\"|null)","");