gpt4 book ai didi

java - 从服务器读取 JSON (Java)

转载 作者:行者123 更新时间:2023-11-29 19:13:40 26 4
gpt4 key购买 nike

首先,很抱歉提出这个愚蠢的问题。

任何人都可以帮我提供有关如何从服务器读取此 JSON 文件的代码吗?看了几个教程后,我搞砸了我的 Java 代码。

[
{
"name": "Coleen Sanford",
"location": {
"latitude": -60.489023,
"longitude": -32.311668
}
},
{
"name": "Bethany Church",
"location": {
"latitude": -1.304805,
"longitude": -80.670287
}
},
{
"name": "Kristy Ware",
"location": {
"latitude": -46.443562,
"longitude": -46.426997
}
},
{
"name": "Avery Navarro",
"location": {
"latitude": 35.719469,
"longitude": -172.783006
}
},
{
"name": "Robyn Cruz",
"location": null
},
{
"name": "Vinson Hays",
"location": null
}
]

这是我的代码:

/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();

}

@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();

// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);

Log.e(TAG, "Response from url: " + jsonStr);

if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);

// Getting JSON Array node
JSONArray contacts = new JSONArray (jsonStr);

// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);

String name = c.getString("name");

// Phone node is JSON Object
JSONObject phone = c.getJSONObject("location");
String latitude = phone.getString("latitude");
String longitude = phone.getString("longitude");

// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();

// adding each child node to HashMap key => value
contact.put("name", name);
contact.put("latitude", latitude);
contact.put("longitude", longitude);

// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});

}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});

}

return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"name", "latitude",
"longitude"}, new int[]{R.id.name,
R.id.latitude, R.id.longitude});

lv.setAdapter(adapter);
}

}}

最佳答案

首先你可以使用Gson这是一个用于序列化和反序列化 Json 的 google powerd 工具

然后在你的代码中添加gson依赖,

    compile 'com.google.code.gson:gson:2.7'

接下来你要做的是创建一些示例模型类来序列化你的 json 数据,使用这个 link并粘贴您的 json 数据并创建相应的类

然后是 java 代码,(假设您的基础模型类名称是 UserLocation

Userlocation

    public class UserLocation{
private Location location;

private String name;

public Location getLocation ()
{
return location;
}

public void setLocation (Location location)
{
this.location = location;
}

public String getName ()
{
return name;
}

public void setName (String name)
{
this.name = name;
}
}

Location

    public class Location {
private double longitude;

private double latitude;

public double getLongitude ()
{
return longitude;
}

public void setLongitude (double longitude)
{
this.longitude = longitude;
}

public double getLatitude ()
{
return latitude;
}

public void setLatitude (double latitude)
{
this.latitude = latitude;
}
}

在代码中

List<UserLocation> userLocationList = Arrays.asList(new Gson().fromJson(yourResponseString, UserLocation[].class));

就是这样,所有内容都在这个 userLocationList

快乐的编码.. :)

关于java - 从服务器读取 JSON (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44346077/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com