簡體   English   中英

解析JSON並將其設置為TextView

[英]Parse JSON and set it to TextView

在我的Android應用程序中,我需要解析JSON。 我從一個網站獲取此JSON。 我想在此JSON中解析一個數組'words'並將其設置為一個TextView。 我有點困惑。 可以通過任何方式向我顯示正確的方式並檢查我的代碼。 謝謝你的幫助!

JSON

在此處輸入圖片說明

MainActivity.java

GoogleMap mGoogleMap;

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

    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if(status!= ConnectionResult.SUCCESS){ // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();

    }else { // Google Play Services are available

        // Getting reference to the SupportMapFragment of activity_location.xml
        SupportMapFragment mSupportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        mGoogleMap = mSupportMapFragment.getMap();

        // Enabling MyLocation Layer of Google Map
        mGoogleMap.setMyLocationEnabled(true);
        mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = mLocationManager.getBestProvider(criteria, true);

        // Getting Current Location
        Location location = mLocationManager.getLastKnownLocation(provider);


        if(location!=null){
            onLocationChanged(location);
        }

        mLocationManager.requestLocationUpdates(provider, 20000, 0, this);
    }
}

@Override
public void onLocationChanged(Location location) {
    // Getting latitude of the current location
    double latitude = location.getLatitude();

    // Getting longitude of the current location
    double longitude = location.getLongitude();

    // Creating a LatLng object for the current location
    LatLng mLatLng = new LatLng(latitude, longitude);


    //Add Marker to current location of devise
    //mGoogleMap.addMarker(new MarkerOptions().position(mLatLng).title("Geolocation system").snippet("Your last current location which was available!").icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_location)));

    // Showing the current location in Google Map
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(mLatLng));

    // Show Zoom buttons
    mGoogleMap.getUiSettings().setZoomControlsEnabled(true);

    // Turns on 3D buildings
    mGoogleMap.setBuildingsEnabled(true);

    // Zoom in the Google Map
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

    //Convert double to String
    String mLatitude = Double.toString(latitude);
    String mLongitude = Double.toString(longitude);

    // URL of what3words service
    String w3w_URL = "http://api.what3words.com/position?key=" + w3w_API_KEY + "&position=" + mLongitude + "," + mLatitude;
    String json = null;
    try {
        json = readUrl(w3w_URL);
    } catch (Exception e) {
        e.printStackTrace();
    }
    JSONResponse response = new Gson().fromJson(json, JSONResponse.class);

    String[]words = response.getWords();

    TextView positionWords = (TextView) findViewById(R.id.location_information);
    positionWords.setText(Arrays.toString(words).replaceAll("\\[|\\]", ""));
}

private String readUrl(String urlString) throws Exception {
    BufferedReader reader = null;
    try {
        URL url = new URL(urlString);
        reader = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer buffer = new StringBuffer();
        int read;
        char[] chars = new char[1024];
        while ((read = reader.read(chars)) != -1)
            buffer.append(chars, 0, read);

        return buffer.toString();
    } finally {
        if (reader != null)
            reader.close();
    }
}

JSONResponse.java:

public class JSONResponse {

    private String[] words;
    long position;

    public String[] getWords() {
        return words;
    }

    public void setWords(String[] words) {
        this.words = words;
    }

    public long getPosition() {
        return position;
    }

    public void setPosition(long position) {
        this.position = position;
    }
}

Logcat錯誤:

04-05 19:56:33.905  21272-21272/ua.com.what3wordsexample E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at ua.com.what3wordsexample.MainActivity$1.success(MainActivity.java:31)
            at ua.com.what3wordsexample.MainActivity$1.success(MainActivity.java:27)
            at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:155)
            at android.app.ActivityThread.main(ActivityThread.java:5454)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
            at dalvik.system.NativeStart.main(Native Method)

您可以使用https://code.google.com/p/google-gson/
使用類似的東西

User user = new Gson().fromJson(userJSON, User.class);

更新:

public class Response {
private String[] words;
private Position position;
private String language;

public String[] getWords() {
    return words;
}

public void setWords(String[] words) {
    this.words = words;
}

public Position getPosition() {
    return position;
}

public void setPosition(Position position) {
    this.position = position;
}

public String getLanguage() {
    return language;
}

public void setLanguage(String language) {
    this.language = language;
}

}

最后:

Response response = new Gson().fromJson(String_response_from_server, Response.class);

String_response_from_server-這是服務器的String響應,在您的代碼中是

  json = mStringBuilder.toString();

之后,您可以輕松獲得所需的信息

String[]words = response.getWords()

更新2

private String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
    URL url = new URL(urlString);
    reader = new BufferedReader(new InputStreamReader(url.openStream()));
    StringBuffer buffer = new StringBuffer();
    int read;
    char[] chars = new char[1024];
    while ((read = reader.read(chars)) != -1)
        buffer.append(chars, 0, read); 

    return buffer.toString();
} finally {
    if (reader != null)
        reader.close();
}
}

用法

String json = readUrl("http://api.what3words.com/position?key=YOURAPIKEY&position=" + mLongitude + "," + mLatitude);
Response response = new Gson().fromJson(json, Response.class);


PS:我看不到您的position數組包含什么內容,因此我放置了一些Position類,如果有相同的值(如單詞),則可以用String[] position;替換它String[] position;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM