How To Just Read Wanted Data From Json In Java & Android
I asked a similar question few days ago about how i could read just wanted data from JSON file in AngularJS, but i gonna do this job in java in android, so I have a problem in read
Solution 1:
change your try block to
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
}
Log.d("Response: ", "> " + line);
try {
JSONObject jsonRootObject = newJSONObject(line);
JSONArray jsonArray = jsonRootObject.optJSONArray("results");
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
data = jsonObject.getString("formatted_address")
}
} catch (JSONException e) {e.printStackTrace();}
return data;
Now you will have valid string to JSONObject
conversion since previously you parsing incomplete string in while loop which isnt valid json.
Solution 2:
You need to wait until all the input has been read. In other words, all of the JSON Handling code should be out of the while loop.
Solution 3:
You can use the JSON library to parse this object:
publicclassJsonValue {
publicstatic void main(String[] args) throwsJSONException {
String jsonString ="{ \"field1\" : \"value1\", \"city\" : \"New York\", \"address\" : \"address1\" }";
JSONObject jsonObject = new JSONObject(jsonString);
String city = jsonObject.getString("city");
System.out.println(city);
}
}
Solution 4:
Or you can use GSON:
Gson gson = new Gson();
Type type = new TypeToken<List<AddressComponents>>() {}.getType();
List<AddressComponents> fromJson = gson.fromJson(json, type);
http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html
Solution 5:
First create this two models:
publicclassResultModel{
publicstring formatted_address;
}
publicclassResponseModel{
public List<ResultModel> results;
}
then get your addresses with:
Gsongson=newGson();
ResponseModelresponse= gson.fromJson(json, ResponseModel.class);
response.results // this is your list of "formatted addresses"
Can be iterated with for cycle or used anywhere. All other json will be ignored.
make sure to include in your gradle:
compile'com.google.code.gson:gson:2.4'
Post a Comment for "How To Just Read Wanted Data From Json In Java & Android"