具有空值的Json数组

时间:2013-02-26 11:57:28

标签: android json android-intent null

我在使用JSON数组时遇到问题,我真的希望有人可以帮助我。

假设我有一个带有JSON数据的课程,我发送了"意图putextra"另一项活动。

在将其发送到另一个活动之前,如何更改null的值?我做了一些打印来发现空值,它们是不同的,例如:

 Monday : null
 Tuesday : 08:30 - 18:00
 Wednesday : 09:00 - 17:00

 **and so on.**

问题是 - >我有所有json数据,我将它们解析为对象,但我想在之前" intent.putextra"并将它们发送到另一个活动找到null并用" Closed"

替换它们

所以它看起来像

 Monday : Closed
 Tuesday : 08:30 - 18:00
 Wednesday : 09:00 - 17:00

修改

public class LocationBased extends ListActivity{

// JSON Node names
private static final String TAG_Location = "location_id";
private static final String TAG_Company = "company_id";
private static final String TAG_NAME = "name";
private static final String TAG_ADDRESS = "address";
private static final String TAG_PLACE = "place";
private static final String TAG_POSTAL = "postal";
private static final String TAG_CITY = "city";
private static final String TAG_MONDAY = "monday";
private static final String TAG_TUESDAY = "tuesday";
private static final String TAG_WEDNESDAY = "wednesday";
private static final String TAG_THURSDAY = "thursday";
private static final String TAG_FRIDAY = "friday";
private static final String TAG_SATURDAY = "saturday";
private static final String TAG_SUNDAY = "sunday";
private static final String TAG_TYPE = "type";
private static final String TAG_LAT = "lat";
private static final String TAG_LNG = "lng";
private static final String TAG_NOCAR = "nocar";
private static final String TAG = "Debug of Project"; // 

private String a;
private String b;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    SQLiteDatabase db = openOrCreateDatabase("mydb.db", Context.MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS gps_kordinater (ID INTEGER PRIMARY KEY AUTOINCREMENT, Latitude REAL, Longitude REAL);");

    String query = "SELECT Latitude,Longitude FROM gps_kordinater WHERE Id = (SELECT MAX(Id) FROM gps_kordinater)";
    Cursor cursor = db.rawQuery(query, null);
    if(cursor != null)
    {
    cursor.moveToFirst();
     a = cursor.getString(0);
     b = cursor.getString(1);
    }

   String url = "http://webservice.XXX.XX/webservice/getLocationList.php?lat="+ a +"&lng="+ b +"";

    Log.d(TAG, "Leyth URL = Lat : " + a +"     Long : " + b); 


    // now enabled if disabled = ingen support for jb aka 4.0
     if (android.os.Build.VERSION.SDK_INT > 9) {
          StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
          StrictMode.setThreadPolicy(policy);
     }



    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
    JSONParser jParser = new JSONParser();
    JSONArray json = jParser.getJSONFromUrl(url);
    try {
           for(int i = 0; i < json.length(); i++){
                JSONObject c = json.getJSONObject(i);

            String location_id = c.getString(TAG_Location);
            String company_id = c.getString(TAG_Company);
            String name = c.getString(TAG_NAME);
            String address = c.getString(TAG_ADDRESS);
            String place = c.getString(TAG_PLACE);  
            String postal = c.getString(TAG_POSTAL);
            String city = c.getString(TAG_CITY);
            String monday = c.getString(TAG_MONDAY);
            String tuesday = c.getString(TAG_TUESDAY);
            String wednesday = c.getString(TAG_WEDNESDAY);  
            String thursday = c.getString(TAG_THURSDAY);
            String friday = c.getString(TAG_FRIDAY);
            String saturday = c.getString(TAG_SATURDAY);
            String sunday = c.getString(TAG_SUNDAY);
            String type = c.getString(TAG_TYPE);
            String lat = c.getString(TAG_LAT);
            String lng = c.getString(TAG_LNG);
            String nocar = c.getString(TAG_NOCAR);


        // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_Location, location_id);
            map.put(TAG_Company, company_id);
            map.put(TAG_NAME, name);
            map.put(TAG_ADDRESS, address);
            map.put(TAG_PLACE, place);
            map.put(TAG_POSTAL, postal);
            map.put(TAG_CITY, city);
            map.put(TAG_MONDAY, monday);
            map.put(TAG_TUESDAY, tuesday);
            map.put(TAG_WEDNESDAY, wednesday);
            map.put(TAG_THURSDAY, thursday);
            map.put(TAG_FRIDAY, friday);
            map.put(TAG_SATURDAY, saturday);
            map.put(TAG_SUNDAY, sunday);
            map.put(TAG_TYPE, type);
            map.put(TAG_LAT, lat);
            map.put(TAG_LNG, lng);
            map.put(TAG_NOCAR, nocar);

        //    Log.d(TAG, "Leyth Days = Mandag : " + monday +"     Onsdag : " + wednesday); 


                // adding HashList to ArrayList
            contactList.add(map);
           }
    } catch (JSONException e) {
        e.printStackTrace();
        Log.e("JSON Parser", "Error parsing data " + e.toString());

    }
    /**
     * Updating parsed JSON data into ListView
     * */
    ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.list_item,
            new String[] { TAG_LAT, TAG_LNG, TAG_POSTAL }, new int[] {
                    R.id.name, R.id.email, R.id.mobile });
    setListAdapter(adapter);

    // selecting single ListView item
    ListView lv = getListView();

    // Launching new screen on Selecting Single ListItem
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
            String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();

            String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();

            String mandag = ((TextView) view.findViewById(R.id.mandag)).getText().toString();
            String tirsdag = ((TextView) view.findViewById(R.id.tirsdag)).getText().toString();
            String onsdag = ((TextView) view.findViewById(R.id.onsdag)).getText().toString();
            String torsdag = ((TextView) view.findViewById(R.id.torsdag)).getText().toString();
            String fredag = ((TextView) view.findViewById(R.id.fredag)).getText().toString();
            String lordag = ((TextView) view.findViewById(R.id.lordag)).getText().toString();
            String sondag = ((TextView) view.findViewById(R.id.sondag)).getText().toString();




            // Starting new intent
            Intent in = new Intent(getApplicationContext(), dk.mitaffald.maps.MainActivity.class);
            in.putExtra(TAG_LAT, name);
            in.putExtra(TAG_LNG, cost);
            in.putExtra(TAG_Company, description);

            in.putExtra(TAG_MONDAY, mandag);
            in.putExtra(TAG_TUESDAY, tirsdag);
            in.putExtra(TAG_WEDNESDAY, onsdag);
            in.putExtra(TAG_THURSDAY, torsdag);
            in.putExtra(TAG_FRIDAY, fredag);
            in.putExtra(TAG_SATURDAY, lordag);
            in.putExtra(TAG_SUNDAY, sondag);


            startActivity(in);

        }
    });
}

}

4 个答案:

答案 0 :(得分:0)

我过去也遇到过这个问题,但我不知道这是一个很好的解决方案,但它对我有用。希望它对你也有用。

String jsonObject_string ;
try {
                if (jsonObject != null) {

                    // ur stuff when not null

                }

            } catch (Exception e) {
                // TODO: handle exception
                                    // when null it automatic fill value 
                jsonObject_string = "Closed";
            }

答案 1 :(得分:0)

在解析JSON文件/对象之前,为什么不尝试将JSON中的所有null字符串替换为字符串?

可能的其他解决方案可能是循环遍历每个对象,检查它们是否为空。然后将其替换为Closed

编辑: 将JSON对象加载为字符串,然后将所有null替换为Closed,如下所示:

String JSON = JsonObject.toString();
JSON.replace("null", "Closed");

编辑2: 在JSONArray json = jParser.getJSONFromUrl(url);下面添加以下内容:

String s = json.toString(); // converts json object to string
json.replace("null", "Closed"); // replaces null for Closed
JSONArray json = new JSONArray(s); // converts back to json object

答案 2 :(得分:0)

据我所知,您想要用特定字符串替换任何空字符串,请说“已关闭”。 这与JSON没有任何关系,如果这是我的代码,我会在将这些值添加到我的意图之前进行简单的检查。代码看起来像这样:

           Intent in = new Intent(getApplicationContext(), dk.mitaffald.maps.MainActivity.class);

        in.putExtra(TAG_LAT, name == null ? "Closed" : name);
        in.putExtra(TAG_LAT, cost== null  ? "Closed" : cost);
        in.putExtra(TAG_Company, description == null  ? "Closed" : description );

        in.putExtra(TAG_MONDAY, mandag == null  ? "Closed" : mandag);
        ....

等等。

name == null? “封闭”:姓名; 简单地询问name是否为null然后关闭值,否则返回name。

它与:

相同
if (name == null){
in.putExtra(TAG_LAT, "Closed");
} else {
in.putExtra(TAG_LAT, name);
}

我希望这就是你要找的东西

答案 3 :(得分:0)

if(c.getString(TAG_MONDAY!=null &&  c.getString(TAG_MONDAY).length>0 && !(c.getString(TAG_MONDAY).equals("")))
{
String monday=c.getString(TAG_MONDAY);
}
else
{
String monday="Closed";
}