这可能是一个愚蠢的问题,但是在Java中从URL读取和解析JSON的最简单的方法是什么?
在Groovy中,这只是几行代码的问题。我发现Java示例长得离谱(并且有巨大的异常处理块)。
我所要做的就是阅读这个链接的内容。
这可能是一个愚蠢的问题,但是在Java中从URL读取和解析JSON的最简单的方法是什么?
在Groovy中,这只是几行代码的问题。我发现Java示例长得离谱(并且有巨大的异常处理块)。
我所要做的就是阅读这个链接的内容。
当前回答
最简单的方法: 使用gson,谷歌自己的goto json库。https://code.google.com/p/google-gson/
这是一个样品。我到这个免费的地理定位器网站,解析json,显示邮政编码。(只要把这些东西放在主方法中测试就可以了)
String sURL = "http://freegeoip.net/json/"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
URLConnection request = url.openConnection();
request.connect();
// 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.
String zipcode = rootobj.get("zip_code").getAsString(); //just grab the zipcode
其他回答
如果你不介意使用几个库,它可以在一行中完成。
包括Apache Commons IOUtils和json.org库。
JSONObject json = new JSONObject(IOUtils.toString(new URL("https://graph.facebook.com/me"), Charset.forName("UTF-8")));
Maven的依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
下面是如何解析Json内容的完整示例。该示例获取Android版本统计信息(从Android Studio源代码中找到,链接到这里)。
复制“发行版”。Json”文件,你从那里得到的res/raw,作为一个后备。
build.gradle
implementation 'com.google.code.gson:gson:2.8.6'
清单
<uses-permission android:name="android.permission.INTERNET" />
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState != null)
return
thread {
// https://cs.android.com/android/platform/superproject/+/studio-master-dev:tools/adt/idea/android/src/com/android/tools/idea/stats/DistributionService.java
var root: JsonArray
Log.d("AppLog", "loading...")
try {
HttpURLConnection.setFollowRedirects(true)
val statsUrl = "https://dl.google.com/android/studio/metadata/distributions.json" //just a string
val url = URL(statsUrl)
val request: HttpURLConnection = url.openConnection() as HttpURLConnection
request.connectTimeout = 3000
request.connect()
InputStreamReader(request.content as InputStream).use {
root = JsonParser.parseReader(it).asJsonArray
}
} catch (e: Exception) {
Log.d("AppLog", "error while loading from Internet, so using fallback")
e.printStackTrace()
InputStreamReader(resources.openRawResource(R.raw.distributions)).use {
root = JsonParser.parseReader(it).asJsonArray
}
}
val decimalFormat = DecimalFormat("0.00")
Log.d("AppLog", "result:")
root.forEach {
val androidVersionInfo = it.asJsonObject
val versionNickName = androidVersionInfo.get("name").asString
val versionName = androidVersionInfo.get("version").asString
val versionApiLevel = androidVersionInfo.get("apiLevel").asInt
val marketSharePercentage = androidVersionInfo.get("distributionPercentage").asFloat * 100f
Log.d("AppLog", "\"$versionNickName\" - $versionName - API$versionApiLevel - ${decimalFormat.format(marketSharePercentage)}%")
}
}
}
}
作为依赖项的替代,你也可以使用这个:
InputStreamReader(request.content as InputStream).use {
val jsonArray = JSONArray(it.readText())
}
还有备用方案:
InputStreamReader(resources.openRawResource(R.raw.distributions)).use {
val jsonArray = JSONArray(it.readText())
}
运行的结果:
loading...
result:
"Ice Cream Sandwich" - 4.0 - API15 - 0.20%
"Jelly Bean" - 4.1 - API16 - 0.60%
"Jelly Bean" - 4.2 - API17 - 0.80%
"Jelly Bean" - 4.3 - API18 - 0.30%
"KitKat" - 4.4 - API19 - 4.00%
"Lollipop" - 5.0 - API21 - 1.80%
"Lollipop" - 5.1 - API22 - 7.40%
"Marshmallow" - 6.0 - API23 - 11.20%
"Nougat" - 7.0 - API24 - 7.50%
"Nougat" - 7.1 - API25 - 5.40%
"Oreo" - 8.0 - API26 - 7.30%
"Oreo" - 8.1 - API27 - 14.00%
"Pie" - 9.0 - API28 - 31.30%
"Android 10" - 10.0 - API29 - 8.20%
这很简单,使用jersey-client,只需要包含这个maven依赖:
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.25.1</version>
</dependency>
然后使用下面的例子调用它:
String json = ClientBuilder.newClient().target("http://api.coindesk.com/v1/bpi/currentprice.json").request().accept(MediaType.APPLICATION_JSON).get(String.class);
然后使用谷歌的Gson来解析JSON:
Gson gson = new Gson();
Type gm = new TypeToken<CoinDeskMessage>() {}.getType();
CoinDeskMessage cdm = gson.fromJson(json, gm);
最简单的方法: 使用gson,谷歌自己的goto json库。https://code.google.com/p/google-gson/
这是一个样品。我到这个免费的地理定位器网站,解析json,显示邮政编码。(只要把这些东西放在主方法中测试就可以了)
String sURL = "http://freegeoip.net/json/"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
URLConnection request = url.openConnection();
request.connect();
// 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.
String zipcode = rootobj.get("zip_code").getAsString(); //just grab the zipcode
我已经用最简单的方式完成了json解析器,下面就是
package com.inzane.shoapp.activity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
System.out.println(line);
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
System.out.println("error on parse data in jsonparser.java");
}
// return JSON String
return jObj;
}
}
该类从url返回json对象
当你想要json对象时,你只需调用这个类和Activity类中的方法
我的代码在这里
String url = "your url";
JSONParser jsonParser = new JSONParser();
JSONObject object = jsonParser.getJSONFromUrl(url);
String content=object.getString("json key");
这里的“json key”指的是json文件中的键
这是一个简单的json文件示例
{
"json":"hi"
}
这里“json”是键,“hi”是值
这将使您的json值字符串内容。