1

我正在尝试将此 JSON 字符串划分为每个联系人项目的单独字符串,例如电子邮件地址和电话号码。我正在使用 System.out.print 来查看信息是否按应有的方式存储在字符串中。system.out 中没有显示任何内容,所发生的一切就是您在下面的 logcat 中看到的。

JSON字符串:

{"items":[{"description":"payment confirmed","emailAddress":"abc@aqw.com","id":"Fri Aug 30 17:20:35 EDT 2013","nameFirst":"Bill","nameLast":"Sanders","phone":"5555555555","state":"KS","streetAddress":"123 Rick Dr","zipCode":"44444","kind":"contactinfoendpoint#resourcesItem"},{"description":"payment confirmed","emailAddress":"qwe@msn.com","id":"Fri Aug 30 17:21:37 EDT 2013","nameFirst":"Frank","nameLast":"Lloyd","phone":"5554567896","state":"KY","streetAddress":"999 Rock St","zipCode":"44555","kind":"contactinfoendpoint#resourcesItem"}],"kind":"contactinfoendpoint#resources","etag":"\"NiDXI3T89oRrAPGJAhgGQje1Z0w/z0W4p01mjHc5cNgcOt3Kb_1xo8E\""}

这是日志猫。

09-03 14:51:18.755: W/System.err(27991): org.json.JSONException: No value for emailAddress
09-03 14:51:18.755: W/System.err(27991):    at org.json.JSONObject.get(JSONObject.java:354)
09-03 14:51:18.755: W/System.err(27991):    at org.json.JSONObject.getString(JSONObject.java:510)
09-03 14:51:18.755: W/System.err(27991):    at com.indeeditis.FinderActivity$EndpointsTask.doInBackground(FinderActivity.java:112)
09-03 14:51:18.765: W/System.err(27991):    at com.indeeditis.FinderActivity$EndpointsTask.doInBackground(FinderActivity.java:1)
09-03 14:51:18.765: W/System.err(27991):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-03 14:51:18.765: W/System.err(27991):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-03 14:51:18.765: W/System.err(27991):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-03 14:51:18.765: W/System.err(27991):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-03 14:51:18.765: W/System.err(27991):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-03 14:51:18.765: W/System.err(27991):    at java.lang.Thread.run(Thread.java:856)

我的程序:

public class FinderActivity extends ListActivity   {


private static final String TAG_ID = "id";
private static final String TAG_FIRSTNAME = "nameFirst";
private static final String TAG_LASTNAME = "nameLast";
private static final String TAG_EMAIL = "emailAddress";
private static final String TAG_ADDRESS = "streetAddress";
private static final String TAG_STATE = "state";

private static final String TAG_PHONE = "phone";
JSONArray contacts = null;



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


    new EndpointsTask().execute(getApplicationContext());

}

public class EndpointsTask extends AsyncTask<Context, Integer, Long> {

    public Long doInBackground(Context... contexts) {

      Contactinfoendpoint.Builder endpointBuilder = new Contactinfoendpoint.Builder(
          AndroidHttp.newCompatibleTransport(),
          new JacksonFactory(),
          new HttpRequestInitializer() {
          public void initialize(HttpRequest httpRequest) { }
          });
  Contactinfoendpoint endpoint = CloudEndpointUtils.updateBuilder(
  endpointBuilder).build();

  try {

    String apples = endpoint.listContactInfo().execute().toString();

    JSONObject jObject = new JSONObject(apples);

    JSONArray jsonArr = jObject.getJSONArray("items");

     for(int i =0 ; i<jsonArr.length() ;i++ ){
         JSONObject jsonObj1 = jsonArr.getJSONObject(i);


                    // Storing each json item in variable
                    String id = jsonObj1.getString(TAG_ID);
                    String nameFirst1 = jsonObj1.getString(TAG_FIRSTNAME);
                    String nameLast1 = jsonObj1.getString(TAG_LASTNAME);
                    String emailAddress1 = jsonObj1.getString(TAG_EMAIL);
                    String streetAddress1 = jsonObj1.getString(TAG_ADDRESS);
                    String phone1 = jsonObj1.getString(TAG_PHONE);

                    //test to see if made it to string

                    System.out.print(nameFirst1);
                    System.out.print(nameLast1);


     }

    } catch (IOException e) {
    e.printStackTrace();
  } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
      return (long) 0;
    }


    }

}

您在 logcat 中的标签。在循环之前验证字符串的内容。

09-03 15:13:57.690: D/YOUR_TAG(30179): [{"streetAddress":"123 Rick Dr","id":"Fri Aug 30 17:20:35 EDT 2013","phone":"5555555555","nameLast":"Sanders","nameFirst":"Bill","description":"payment confirmed","zipCode":"44444","state":"KS","emailAddress":"abc@aqw.com","kind":"contactinfoendpoint#resourcesItem"},{"streetAddress":"999 Rock St","id":"Fri Aug 30 17:21:37 EDT 2013","phone":"5554567896","nameLast":"Lloyd","nameFirst":"Frank","description":"payment confirmed","zipCode":"44555","state":"KY","emailAddress":"qwe@msn.com","kind":"contactinfoendpoint#resourcesItem"},{"id":"Sat Aug 31 12:46:33 EDT 2013","nameLast":"j","nameFirst":"j","kind":"contactinfoendpoint#resourcesItem","description":"payment confirmed"},{"id":"Sat Aug 31 14:33:03 EDT 2013","emailAddress":"c","nameLast":"b","nameFirst":"a","kind":"contactinfoendpoint#resourcesItem","description":"payment confirmed"}]

好的,我已经从我的数据存储中删除了后面的条目。我现在没有收到任何错误,但我没有得到任何我正在寻找的系统输出。

4

4 回答 4

1

我知道答案已经被接受,您也可以考虑使用 GSON 库。

IT 完全按照您的意愿行事,并且有大量的文档和示例,并且该库甚至有很好的文档记录:

https://code.google.com/p/google-gson/

http://www.javacreed.com/simple-gson-example/

希望这对您未来的项目有所帮助。

于 2013-09-03T20:58:58.603 回答
1

看起来您正在假设数组中的每个对象将拥有哪些数据。其中一个对象没有所有数据,这会引发错误。我猜你的错误是在以下几行之一:

String id = jsonObj1.getString(TAG_ID);
String nameFirst1 = jsonObj1.getString(TAG_FIRSTNAME);
String nameLast1 = jsonObj1.getString(TAG_LASTNAME);
String emailAddress1 = jsonObj1.getString(TAG_EMAIL);
String streetAddress1 = jsonObj1.getString(TAG_ADDRESS);
String phone1 = jsonObj1.getString(TAG_PHONE);

由于您没有看到任何打印的内容,请设置一个断点并在您第一次进入 for 循环时验证每条数据是否确实存在。此外,我建议您在尝试抓取之前进行一些防御性编码并使用 has() 来验证 jsonObject 是否确实具有数据,这样您以后就不会得到这些堆栈跟踪。就像是

String id = "";
if (jsonObj1.has(TAG_ID)) {
   id = jsonObj1.getString(TAG_ID);
} else {
   ///Handle bad data
}
于 2013-09-03T19:13:22.623 回答
1

您可以使用droidQuery来简化解析:

Object[] array = $.makeArray(jsonArr);
for (Object obj : array)
{
    Map<String, ?> map = $.map((JSONObject) obj);
    for (Map.Entry<String, ?> entry : map)
    {
        Log.d("DEBUG", String.format(Locale.US, "Object contains Key %s and value %s", entry.getKey(), entry.getValue().toString());
    }
}
于 2013-09-03T19:14:32.267 回答
1

如您所见,您没有为第三个对象定义任何 emailAddress。如果您不确定 JSON 中是否包含所有属性,则必须先检查密钥。

if (jsonObject.has(TAG)) {
    jsonObject.getString(TAG_ID);
}

有时我会使用 utils 来简化代码,例如:

public static String getString(JSONObject object, String tag, String defString) {
    if (object.has(tag))
        return object.getString(tag);
    else
        return defString;
}

所以我的代码将如下所示:

String nameFirst1 = Utils.getString(jsonObj1, TAG_ID, ""); // your firstName default.
String nameLast1 = Utils.getString(jsonObj1, TAG_ID, null); // maybe null??

您的 JSON 格式,使用此链接查看它的格式(它对我有很大帮助)

[
   {
      "streetAddress":"123 Rick Dr",
      "id":"Fri Aug 30 17:20:35 EDT 2013",
      "phone":"5555555555",
      "nameLast":"Sanders",
      "nameFirst":"Bill",
      "description":"payment confirmed",
      "zipCode":"44444",
      "state":"KS",
      "emailAddress":"abc@aqw.com",
      "kind":"contactinfoendpoint#resourcesItem"
   },
   {
      "streetAddress":"999 Rock St",
      "id":"Fri Aug 30 17:21:37 EDT 2013",
      "phone":"5554567896",
      "nameLast":"Lloyd",
      "nameFirst":"Frank",
      "description":"payment confirmed",
      "zipCode":"44555",
      "state":"KY",
      "emailAddress":"qwe@msn.com",
      "kind":"contactinfoendpoint#resourcesItem"
   },
   {
      "id":"Sat Aug 31 12:46:33 EDT 2013",
      "nameLast":"j",
      "nameFirst":"j",
      "kind":"contactinfoendpoint#resourcesItem",
      "description":"payment confirmed"
   },
   {
      "id":"Sat Aug 31 14:33:03 EDT 2013",
      "emailAddress":"c",
      "nameLast":"b",
      "nameFirst":"a",
      "kind":"contactinfoendpoint#resourcesItem",
      "description":"payment confirmed"
   }
]
于 2013-09-03T19:18:27.823 回答