2015-04-04 82 views
-1

在我的android应用程序中,我需要解析JSON。从一个网站我拿这个JSON。我想解析这个JSON中的数组'单词',并将其设置为一个TextView。我有点困惑。有什么方法可以让我正确地看到并检查我​​的代码。谢谢你的帮助!解析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) 
+0

最新的问题是什么? – 2015-04-04 10:06:27

+0

你是否收到任何错误,如果是请发布例外 – 2015-04-04 10:06:47

+0

你的代码很好,并且正常工作,pl分享你正面临的实际问题 – 2015-04-04 10:15:36

回答

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 - 这是从服务器的字符串响应,在你的代码是

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


附:我看不到包含你的位置数组的东西,所以我调用了一些类的位置,如果有相同的数值就像在文字中可以替换它String[] position;

相关问题