在Java Android App中使用从Webserver检索到的JSON动态创建和使用对象的步骤如下:
下面是一个示例代码,演示了如何在Java Android App中使用从Webserver检索到的JSON动态创建和使用对象:
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 发送HTTP请求并获取JSON数据
new FetchDataAsyncTask().execute("http://example.com/data.json");
}
private class FetchDataAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String result = "";
HttpURLConnection urlConnection = null;
try {
URL url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
result = stringBuilder.toString();
} catch (IOException e) {
Log.e(TAG, "Error fetching data", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return result;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (!result.isEmpty()) {
try {
// 解析JSON数据
JSONArray jsonArray = new JSONArray(result);
List<MyObject> objects = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
MyObject object = new MyObject(name, age);
objects.add(object);
}
// 在应用程序中使用对象
for (MyObject object : objects) {
Log.d(TAG, "Name: " + object.getName() + ", Age: " + object.getAge());
}
} catch (JSONException e) {
Log.e(TAG, "Error parsing JSON", e);
}
}
}
}
private class MyObject {
private String name;
private int age;
public MyObject(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
}
这个示例代码演示了如何使用AsyncTask来发送HTTP请求并获取JSON数据。然后,它解析JSON数据并将其转换为MyObject对象的列表。最后,它在日志中打印了每个对象的名称和年龄。
请注意,这只是一个简单的示例,你可以根据你的实际需求进行修改和扩展。另外,你可能需要处理网络请求的错误和异常情况,以及在UI线程中更新UI界面等其他操作。
领取专属 10元无门槛券
手把手带您无忧上云