我正在尝试解析一些JSON。我最近一直试图在android studio中使用 GSON 这样做。但是,我似乎无法获得连接或对数据做任何事情。我想看的数据,如果我能从网站上获得它,将会是这样的:
{"item":{"icon":"address_here",
id=820","id":820,"type":"Default",
"typeIcon":"catagory","name":"Name of Object",
"description":"This is an annoying issue to get stuck on"}}
我一直在使用异步,但无济于事。也许一种看待这种情况的新方法会很好。
这是我目前的代码:
public class JavaParser extends AsyncTask<String, String, String> {
public String getInternetData() throws Exception {
String sURL = "someurl.com"; //just a string
// Connect to the URL using java's native library
try {
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
Log.d("Debug:", "Made partial connection");
try {
request.connect();
} catch (IOException e1) {
e1.printStackTrace();
}
Log.d("Debug:", "Made connection");
}
catch(Exception e){
}
return "FAILURE";
}
private String response = null;
@Override
protected String doInBackground(String...params) {
try {
response = new JavaParser().getInternetData();
}
catch(Exception e){
Log.d("Error",e.getMessage()
);
}
return response;
}
}
在我的主要课程中:
String response = new JavaParser().execute("URL").get(); //eventually I hope to pass the url here to be more dynamic
//Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.
Gson gson = new Gson();
Wrapper response = gson.fromJson(rootobj, Wrapper.class);
Log.d("Out: ",rootobj.get("item\name").getAsString()); //just grab the name info
我的包装看起来像这样:
public class Wrapper {
@SerializedName("name")
public String item_name;
@SerializedName("icon")
public String iconURL;
@SerializedName("description")
public String item_description;
//more to be added if it works
}
程序只进行部分连接。我似乎无法得到这条线 request.connect(); 无论如何运作。
答案 0 :(得分:0)
事实证明,许可是清单的错误部分。它需要靠近顶部,我把它作为这样的
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yargonauts.burk.app">
<uses-permission android:name="android.permission.INTERNET" />