Rol*_*lig 187
使用Maven工件org.json:json
我得到了以下代码,我认为这很短.尽可能短,但仍然可用.
package so4308554;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonReader {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("https://graph.facebook.com/19292868552");
System.out.println(json.toString());
System.out.println(json.get("id"));
}
}
Run Code Online (Sandbox Code Playgroud)
Sta*_*Man 64
以下是Jackson的几个替代版本(因为您可能有多种方法需要数据):
ObjectMapper mapper = new ObjectMapper(); // just need one
// Got a Java class that data maps to nicely? If so:
FacebookGraph graph = mapper.readValue(url, FaceBookGraph.class);
// Or: if no class (and don't need one), just map to Map.class:
Map<String,Object> map = mapper.readValue(url, Map.class);
Run Code Online (Sandbox Code Playgroud)
特别是你想要处理Java对象的通常(IMO)情况,可以做成一个班轮:
FacebookGraph graph = new ObjectMapper().readValue(url, FaceBookGraph.class);
Run Code Online (Sandbox Code Playgroud)
像Gson这样的其他lib也支持单行方法; 为什么许多例子显示更长的部分是奇怪的.更糟糕的是,许多示例使用过时的org.json库; 它可能是第一件事,但有六个更好的替代品,所以几乎没有理由使用它.
use*_*569 58
最简单的方法:使用gson,谷歌自己的goto json库.https://code.google.com/p/google-gson/
这是一个例子.我要去这个免费的geolocator网站并解析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
Run Code Online (Sandbox Code Playgroud)
ezw*_*ter 40
如果您不介意使用几个库,可以在一行中完成.
包括Apache Commons IOUtils和json.org库.
JSONObject json = new JSONObject(IOUtils.toString(new URL("https://graph.facebook.com/me"), Charset.forName("UTF-8")));
Run Code Online (Sandbox Code Playgroud)
使用HttpClient获取URL的内容.然后使用json.org中的库来解析JSON.我在很多项目中使用了这两个库,它们非常强大且易于使用.
除此之外,您可以尝试使用Facebook API java库.我在这方面没有任何经验,但是有一个关于在Java中使用Facebook API的堆栈溢出的问题.您可能希望将RestFB视为库使用的不错选择.
小智 5
我以最简单的方式完成了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;
}
}
Run Code Online (Sandbox Code Playgroud)
此类从url返回json对象
当你想要json对象时,你只需要在Activity类中调用这个类和方法
我的代码在这里
String url = "your url";
JSONParser jsonParser = new JSONParser();
JSONObject object = jsonParser.getJSONFromUrl(url);
String content=object.getString("json key");
Run Code Online (Sandbox Code Playgroud)
这里"json key"表示你的json文件中的键
这是一个简单的json文件示例
{
"json":"hi"
}
Run Code Online (Sandbox Code Playgroud)
这里"json"是关键,"hi"是价值
这将使您的json值变为字符串内容.
我发现这是迄今为止最简单的方法。
使用这个方法:
public static String getJSON(String url) {
HttpsURLConnection con = null;
try {
URL u = new URL(url);
con = (HttpsURLConnection) u.openConnection();
con.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (con != null) {
try {
con.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
String json = getJSON(url);
JSONObject obj;
try {
obj = new JSONObject(json);
JSONArray results_arr = obj.getJSONArray("results");
final int n = results_arr.length();
for (int i = 0; i < n; ++i) {
// get the place id of each object in JSON (Google Search API)
String place_id = results_arr.getJSONObject(i).getString("place_id");
}
}
Run Code Online (Sandbox Code Playgroud)
Oracle 文档描述了如何
仅使用 Java 类库,只需几行代码。将此代码放入您的 main 方法中:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com/"))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
Run Code Online (Sandbox Code Playgroud)
响应由 JSON 对象 { ... } 组成,可以在您的应用程序中进一步处理。这里我将其打印到控制台,只是为了确认它是否有效:
System.out.println(request);
Run Code Online (Sandbox Code Playgroud)
这适用于 Java 版本 11+
归档时间: |
|
查看次数: |
444374 次 |
最近记录: |