解析JSON并将其设置为TextView

时间:2015-04-04 09:54:30

标签: java android json parsing gson

在我的android应用程序中,我需要解析JSON。从一个网站我拿这个JSON。我想在此JSON中解析数组' 并将其设置为一个TextView。我有点困惑。可以任何方式向我显示正确的方式并检查我的代码。谢谢你的帮助!

JSON

enter image description here

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)

1 个答案:

答案 0 :(得分:2)

您可以使用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()

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

<强>用法

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


P.S。我看不到包含你的位置数组的内容所以我在一些课程中选择了位置,如果有相同的值,就像在单词中你可以用String[] position;替换它