2016-12-26 11 views
0
package info.androidhive.jsonparsing; 

import android.app.ProgressDialog; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.Toast; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.util.ArrayList; 
import java.util.HashMap; 

public class MainActivity extends AppCompatActivity { 

private String TAG = MainActivity.class.getSimpleName(); 

private ProgressDialog pDialog; 
private ListView lv; 

// URL to get contacts JSON 
private static String url = "http://api.androidhive.info/contacts/"; 

ArrayList<HashMap<String, String>> contactList; 

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

    contactList = new ArrayList<>(); 

    lv = (ListView) findViewById(R.id.list); 

    new GetContacts().execute(); 
} 

/** 
* Async task class to get json by making HTTP call 
*/ 
private class GetContacts extends AsyncTask<Void, Void, Void> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     // Showing progress dialog 
     pDialog = new ProgressDialog(MainActivity.this); 
     pDialog.setMessage("Please wait..."); 
     pDialog.setCancelable(false); 
     pDialog.show(); 

    } 

    @Override 
    protected Void doInBackground(Void... arg0) { 
     HttpHandler sh = new HttpHandler(); 

     // Making a request to url and getting response 
     String jsonStr = sh.makeServiceCall(url); 

     Log.e(TAG, "Response from url: " + jsonStr); 

     if (jsonStr != null) { 
      try { 
       JSONObject jsonObj = new JSONObject(jsonStr); 

       // Getting JSON Array node 
       JSONArray contacts = jsonObj.getJSONArray("contacts"); 

       // looping through All Contacts 
       for (int i = 0; i < contacts.length(); i++) { 
        JSONObject c = contacts.getJSONObject(i); 

        String id = c.getString("id"); 
        String name = c.getString("name"); 
        String email = c.getString("email"); 
        String address = c.getString("address"); 
        String gender = c.getString("gender"); 

        // Phone node is JSON Object 
        JSONObject phone = c.getJSONObject("phone"); 
        String mobile = phone.getString("mobile"); 
        String home = phone.getString("home"); 
        String office = phone.getString("office"); 

        // tmp hash map for single contact 
        HashMap<String, String> contact = new HashMap<>(); 

        // adding each child node to HashMap key => value 
        contact.put("id", id); 
        contact.put("name", name); 
        contact.put("email", email); 
        contact.put("mobile", mobile); 

        // adding contact to contact list 
        contactList.add(contact); 
       } 
      } catch (final JSONException e) { 
       Log.e(TAG, "Json parsing error: " + e.getMessage()); 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         Toast.makeText(getApplicationContext(), 
           "Json parsing error: " + e.getMessage(), 
           Toast.LENGTH_LONG) 
           .show(); 
        } 
       }); 

      } 
     } else { 
      Log.e(TAG, "Couldn't get json from server."); 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        Toast.makeText(getApplicationContext(), 
          "Couldn't get json from server. Check LogCat for possible errors!", 
          Toast.LENGTH_LONG) 
          .show(); 
       } 
      }); 

     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     super.onPostExecute(result); 
     // Dismiss the progress dialog 
     if (pDialog.isShowing()) 
      pDialog.dismiss(); 
     /** 
     * Updating parsed JSON data into ListView 
     * */ 
     ListAdapter adapter = new SimpleAdapter(
       MainActivity.this, contactList, 
       R.layout.list_item, new String[]{"name", "email", 
       "mobile"}, new int[]{R.id.name, 
       R.id.email, R.id.mobile}); 

     lv.setAdapter(adapter); 
    } 

} 

}Wie kann ich schreiben Android Json Parsing ohne Array-Name

Dies ist der Code i Internet gefunden. Es funktioniert gut, aber mein Problem ist es, Arrays mit einem Array-Namen zu bekommen. Hier ist die Json url: http://api.androidhive.info/contacts/

Und diese App hat auch eine andere Klasse namens Httphandler:

package info.androidhive.jsonparsing; 

import android.util.Log; 

import java.io.BufferedInputStream; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.ProtocolException; 
import java.net.URL; 

public class HttpHandler { 

private static final String TAG = HttpHandler.class.getSimpleName(); 

public HttpHandler() { 
} 

public String makeServiceCall(String reqUrl) { 
    String response = null; 
    try { 
     URL url = new URL(reqUrl); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setRequestMethod("GET"); 
     // read the response 
     InputStream in = new BufferedInputStream(conn.getInputStream()); 
     response = convertStreamToString(in); 
    } catch (MalformedURLException e) { 
     Log.e(TAG, "MalformedURLException: " + e.getMessage()); 
    } catch (ProtocolException e) { 
     Log.e(TAG, "ProtocolException: " + e.getMessage()); 
    } catch (IOException e) { 
     Log.e(TAG, "IOException: " + e.getMessage()); 
    } catch (Exception e) { 
     Log.e(TAG, "Exception: " + e.getMessage()); 
    } 
    return response; 
} 

private String convertStreamToString(InputStream is) { 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(); 

    String line; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line).append('\n'); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      is.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return sb.toString(); 
} 

}

Mein Problem ist, wie ich diese Codes auf eine andere URL bearbeiten können. Meine JSON-URL ist hier: http://mysafeinfo.com/api/data?list=englishmonarchs&format=json

Wie Sie sehen können, gibt es keinen Array-Namen. Wie kann ich damit fertig werden? Jede Hilfe wird gern gesehen

+0

besuchen Sie diesen Link: http://stackoverflow.com/questions/9598707/gson-throwing-erwartete-begin-object-but-was-begin-array/38351872#38351872 –

Antwort

1

Es ist wirklich einfach, dass man nur Objekt JSONArray erhalten müssen direkt wie folgt aus:

`

@Override 
protected Void doInBackground(Void... arg0) { 
    HttpHandler sh = new HttpHandler(); 

    // Making a request to url and getting response 
    String jsonStr = sh.makeServiceCall(url); 

    Log.e(TAG, "Response from url: " + jsonStr); 

    if (jsonStr != null) { 
     try { 
      // Getting JSON Array node 
      JSONArray contacts = new JSONArray(jsonStr); 

      // looping through All Contacts 
      for (int i = 0; i < contacts.length(); i++) { 
       JSONObject c = contacts.getJSONObject(i); 

       String id = c.getString("nm"); 
       String name = c.getString("cty"); 
       String email = c.getString("hse"); 
       String address = c.getString("yrs"); 


       // tmp hash map for single contact 
       HashMap<String, String> contact = new HashMap<>(); 

       // adding each child node to HashMap key => value 
       contact.put("id", id); 
       contact.put("name", name); 
       contact.put("email", email); 
       contact.put("address", address); 

       // adding contact to contact list 
       contactList.add(contact); 
      } 
     } catch (final JSONException e) { 
      Log.e(TAG, "Json parsing error: " + e.getMessage()); 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        Toast.makeText(getApplicationContext(), 
          "Json parsing error: " + e.getMessage(), 
          Toast.LENGTH_LONG) 
          .show(); 
       } 
      }); 

     } 
    } else { 
     Log.e(TAG, "Couldn't get json from server."); 
     runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       Toast.makeText(getApplicationContext(), 
         "Couldn't get json from server. Check LogCat for possible errors!", 
         Toast.LENGTH_LONG) 
         .show(); 
      } 
     }); 

    } 

    return null; 
} 

` Versuchen Sie, diese ..... hoffe, es wird für Sie arbeiten.

+0

Danke so viel, es funktioniert! – Unicepter

+0

Jederzeit willkommen **:) ** – Ashish

0

Verwenden

JsonArray listItem = new JsonArray(responseString); 

Keine Notwendigkeit Namen.

+0

Okay Vielen Dank, aber wie kann ich dies setzen in meinen Codes? Eigentlich weiß ich sehr wenig über in android Studio Codierung .. – Unicepter

+0

JsonArray listItem = new JsonArray (makeServiceCall ("http://mysafeinfo.com/api/data?list=englishmonarchs&format=json)); Probieren Sie es – TruongHieu

0

Es gibt auch eine einfache Lösung. Sie können Google-Gson-Bibliothek verwenden, um Json zu analysieren. Alles, was Sie tun müssen, ist eine Klasse nach dem json-Format zu erstellen. I-e-Variablennamen wie der Name von json-Objekten in json string/file.