I need to take the values from a JSON array and display them. Below is the code I have used.
`getresponse` class will send a HTTP request to a PHP page and get the relevant JSON array and the public variable **res** will hold that returned JSON array.
public class JSONConverter {
public void convert(){
getresponse gr=new getresponse();
String json = gr.res;
Data data = new Gson().fromJson(json, Data.class);
System.out.println(data);
}
}
class Data {
private String city;
private int reserve_no;
public String getCity() { return city; }
public int getReserve_no() { return reserve_no; }
public void setTitle(String city) { this.city = city; }
public void setId(int reserve_no) { this.reserve_no = reserve_no; }
public String toString() {
return String.format(city);
}
}
**getrespose class**
public class getresponse {
public static String res;
public void counter() {
try {
URL url = new URL("http://taxi.net/fetchLatest.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String str;
while ((str =br.readLine()) != null) {
res=str;
}
conn.disconnect();
Below is an example of JSON array returned.
> [{"reserve_no":"20","city":"city2","street":"street1234","discription":"discription123","date":"2012-10-22
> 04:47:54","customer":"abc"}]
This code doesn't display the city name of the JSON array returned. can someone help me with this by correcting the code or suggest a better or easier method if any? :) There is absolutely no correlation between your Data class and the returned JSON, so how would GSON know what it should do? You should probably create a more appropriate Data class, with fields matching the names of the fields in the JSON string.
以上就是how to convert the values from a json array to a java string的详细内容,更多请关注web前端其它相关文章!