简体   繁体   中英

Parse JSON and set it to TextView

In my android application I need to parse JSON. From one website I take this JSON. I want to parse an array 'words' in this JSON and set it to one TextView. I am little bit confused. Can any way show me right way and check my code. Thanks for any help!

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 error:

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)

You can use https://code.google.com/p/google-gson/
Use something like that

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

Update:

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;
}

}

Finally:

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

String_response_from_server - it's your String response from server, in your code it's

  json = mStringBuilder.toString();

After that you can easily get needed information

String[]words = response.getWords()

Update2

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();
}
}

Usage :

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


PS I can't see what contains your position array so I puted some class Position, if there are the same values like in words you can replase it with String[] position;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM