0

我尝试使用下面的代码来解析 JSON 数据,该网站需要一个 API 密钥,现在它作为字符串存储在我的 strings.xml 中。

public class JSONParser {

static InputStream is = null;
static JSONArray jarray = null;
static String json = "";

// constructor
public JSONParser() {
}

public JSONArray 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 {

        JSONObject jObj = new JSONObject(json);
        jarray = jObj.getJSONArray("systems");
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jarray;
}
}

主要活动。

 public class MainActivity extends ListActivity {
private Context context;
private static String url = "https://api.company.com/api/systems";

private static final String TAG_SYSTEM = "systems";
private static final String TAG_SYSTEM_ID = "system_id";

ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();

ListView lv ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new ProgressTask(MainActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
    private ProgressDialog dialog;

    private ListActivity activity;

    // private List<Message> messages;
    public ProgressTask(ListActivity activity) {
        this.activity = activity;
        context = activity;
        dialog = new ProgressDialog(context);
    }

    /** progress dialog to show user that the backup is processing. */
    private Context context;

    protected void onPreExecute() {
        this.dialog.setMessage("Progress start");
        this.dialog.show();
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        ListAdapter adapter = new SimpleAdapter(context, jsonlist,          
        R.layout.list_item, new String[] { TAG_SYSTEM, TAG_SYSTEM_ID
                 }, new int[] {
                R.id.vehicleType, R.id.vehicleColor });

        setListAdapter(adapter);
        // selecting single ListView item
         lv = getListView();
    }
    protected Boolean doInBackground(final String... args) {

        JSONParser jParser = new JSONParser();
        //Using APIKEY from strings.xml
        String apikey = getString(R.string.apikey);
        // getting JSON string from URL
        JSONArray json = jParser.getJSONFromUrl(url + "&key=" + apikey);

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

            try {
                JSONObject c = json.getJSONObject(i);

                String vcolor = c.getString(TAG_SYSTEM_ID);

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

                // adding each child node to HashMap key => value
                map.put(TAG_SYSTEM_ID, vcolor);
                jsonlist.add(map);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
}

}

这是我当前的 LogCat

  04-30 15:39:53.775: E/JSON Parser(9814): Error parsing data org.json.JSONException: Value   <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
04-30 15:39:53.780: E/AndroidRuntime(9814): FATAL EXCEPTION: AsyncTask #1
04-30 15:39:53.780: E/AndroidRuntime(9814): java.lang.RuntimeException: An error occured while executing doInBackground()
04-30 15:39:53.780: E/AndroidRuntime(9814):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.lang.Thread.run(Thread.java:856)
04-30 15:39:53.780: E/AndroidRuntime(9814): Caused by: java.lang.NullPointerException
04-30 15:39:53.780: E/AndroidRuntime(9814):     at com.jitesh.androidjsonparser.MainActivity$ProgressTask.doInBackground(MainActivity.java:102)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at com.jitesh.androidjsonparser.MainActivity$ProgressTask.doInBackground(MainActivity.java:1)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-30 15:39:53.780: E/AndroidRuntime(9814):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-30 15:39:53.780: E/AndroidRuntime(9814):     ... 5 more
04-30 15:40:03.035: E/WindowManager(9814): Activity com.jitesh.androidjsonparser.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4257ae80 that was originally added here
04-30 15:40:03.035: E/WindowManager(9814): android.view.WindowLeaked: Activity com.jitesh.androidjsonparser.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4257ae80 that was originally added here
04-30 15:40:03.035: E/WindowManager(9814):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:402)
04-30 15:40:03.035: E/WindowManager(9814):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:311)
04-30 15:40:03.035: E/WindowManager(9814):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
04-30 15:40:03.035: E/WindowManager(9814):  at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
04-30 15:40:03.035: E/WindowManager(9814):  at android.view.Window$LocalWindowManager.addView(Window.java:554)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.Dialog.show(Dialog.java:277)
04-30 15:40:03.035: E/WindowManager(9814):  at com.jitesh.androidjsonparser.MainActivity$ProgressTask.onPreExecute(MainActivity.java:69)
04-30 15:40:03.035: E/WindowManager(9814):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
04-30 15:40:03.035: E/WindowManager(9814):  at android.os.AsyncTask.execute(AsyncTask.java:534)
04-30 15:40:03.035: E/WindowManager(9814):  at com.jitesh.androidjsonparser.MainActivity.onCreate(MainActivity.java:47)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.Activity.performCreate(Activity.java:5206)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.ActivityThread.access$600(ActivityThread.java:140)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
04-30 15:40:03.035: E/WindowManager(9814):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 15:40:03.035: E/WindowManager(9814):  at android.os.Looper.loop(Looper.java:137)
04-30 15:40:03.035: E/WindowManager(9814):  at android.app.ActivityThread.main(ActivityThread.java:4898)
04-30 15:40:03.035: E/WindowManager(9814):  at java.lang.reflect.Method.invokeNative(Native Method)
04-30 15:40:03.035: E/WindowManager(9814):  at java.lang.reflect.Method.invoke(Method.java:511)
04-30 15:40:03.035: E/WindowManager(9814):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
04-30 15:40:03.035: E/WindowManager(9814):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
04-30 15:40:03.035: E/WindowManager(9814):  at dalvik.system.NativeStart.main(Native Method)

有人可以帮我解决我遇到的这些问题。如果您花时间阅读和帮助,请提前感谢您。


WiiMaxx,

听起来您正试图以线性方式显示深层对象图,这对于 DataGrid 来说可能非常麻烦。我能够通过从我的实体基类上的 DynamicObject 继承来应对这一挑战(在这种情况下我使用的是实体框架)。如果您不熟悉 DynamicObject,您可以在此链接中了解它

http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx

本质上,它允许您做的是使用属性包来存储动态属性,这些动态属性将在运行时使用动态类型在您的对象上出现和继续。当您需要将图形展平以在数据网格中显示时,这是一个很好的解决方案。您只需要确保覆盖 TryGetMember 和 TrySetMember 方法。这在与数据绑定结合使用时特别漂亮,因为您可以在运行时添加/删除成员,并且通过数据绑定,WPF 将尝试通过那些覆盖的方法访问/更新这些成员。

public class EntityBase : DynamicObject, INotifyPropertyChanged
{
    public Dictionary<string, object> DynamicProperties { get; set; }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    /// <summary>
    /// Raises this object's PropertyChanged event.
    /// </summary>
    /// <param name="propertyName">The property that has a new value.</param>
    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (!HasProperty(propertyName))
        {
            return;
        }

        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
        {
            var e = new PropertyChangedEventArgs(propertyName);
            handler(this, e);
        }
    }

    public bool HasProperty(string propertyName)
    {
        // Verify that the property name matches a real,  
        // public, instance property on this object.
        if (TypeDescriptor.GetProperties(this)[propertyName] != null)
        {
            return true;
        }

        return false;
    }

    #endregion


    #region Ctor

    public EntityBase()
    {
        this.DynamicProperties = new Dictionary<string, object>();
    }

    #endregion


    #region DynamicObject Overrides

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        string name = binder.Name.ToLower();

        return this.DynamicProperties.TryGetValue(name, out result);
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        this.DynamicProperties[binder.Name.ToLower()] = value;

        OnPropertyChanged(binder.Name);

        return true;
    }

    #endregion
}

现在,使用它作为模型类型的基类,您可以在运行时添加/删除成员并仍然利用 WPF 数据绑定。

所以接下来我们需要展平我们的图表。ViewModelBase 下面的基类简单地实现了 INotifyPropertyChanged。

public class YourViewModel : ViewModelBase
{
    private YourDeepObjectGraphClass _instance;
    public YourDeepObjectGraphClass Instance
    {
        get { return _yourClass; }
        set
        {
            _yourClass = value;

            OnPropertyChanged("Instance");
        }
    }

    public void FlattenGraph()
    {
        foreach (IEnumerable<DeepObjectGraphType> t in Instance.List)
        {
            ((dynamic)Instance).YourDynamicProperty = t.SomeProperty;
        }
    }
}

现在,在您的视图中,您可以将控件(ItemsControl、DataGrid)上的绑定设置为“YourDynamicProperty”,并且 WPF 将为您呈现它,前提是您在后面的代码中调用了 InitializeComponent 之后调用了 FlattenGraph。

希望对您有所帮助,如果您有任何问题,请告诉我。

4

2 回答 2

0

这是来自您的服务器的错误。您想通过调用 httpResponse.getStatusLine().getStatusCode() 检查状态码

如果状态码是 200,那么你就可以开始解析你的结果了。否则,这是一个错误,你必须优雅地处理错误。

于 2013-04-30T23:38:38.303 回答
0

该服务显然会返回服务器错误。尝试从可以看到响应的客户端使用相同的参数调用服务,或者在尝试将其解析为 JSON 之前记录字符串响应。确切的服务器响应肯定会告诉您查询出了什么问题。

于 2013-04-30T23:00:38.903 回答