벙어리 줄 수도 있지만 이 질문을 읽고 구문 URL 에서 가장 간단한 방법은 지정하십시오. JSON 의 java를?
All I want to do 컨텐트에서 읽을 수 있다 (이 링크] 1.
메이븐 '유물' 나는 attaboy 를 사용하여 다음과 같은 코드를 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"));
}
}
다음은 몇 가지 대안을 버전으로 잭슨 (이후 둘 이상의 방법으로 데이터로 확인할 수 있습니다).
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);
일반적인 경우, 특히 국제해사기구 (imo) where you want to 계약을 한 liner jave 오브젝트에도 만들 수 있습니다.
FacebookGraph graph = new ObjectMapper().readValue(url, FaceBookGraph.class);
또한 같은 다른 libs 그슨 지원부에서는 한 방법. 왜 홀수입니다 단면에는 는 훨씬 더 많은 보여 줍니다. 심지어 더 심한 것은 여러 가지 비활용 오르g.j슨 사용하여 라이브러리. 그동안 가장 먼저 한 일은 있을 수 있어 주위를 더 나은 대안을 수축됐는데 반단면 수십 이유는 거의 사용할 수 있습니다.
가장 쉬운 방법은. Google& # 39 의 고유한 이동, json 라이브러리를 사용하여, 그슨. https://code.google.com/p/google-gson/
예를 들면 다음과 같습니다. # 39 i&, m 이 무료 웹 사이트 및 분석 및 디스플레이하여 내 우편번호를 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.org) 으로 명명한다.
JSONObject json = new JSONObject(IOUtils.toString(new URL("https://graph.facebook.com/me"), Charset.forName("UTF-8")));
하테프클리나 사용하여 잡기 위한 컨텐트에서 uirl. 다음 라이브러리에서 json.org 구문 분석을 위해 JSON. 그러나 그동안 이 두 라이브러리, ve i& # 39 에 사용되는 많은 프로젝트와 강력하고 간단한 사용할 수 있습니다.
페이스북 API 는 자바 라이브러리를 사용하여 아닌 다른 볼 수 있습니다. # 39) 이 있는데, 이 분야에 경험이 별로 없는 내가 don& 대한 질문을 받고, 스택 오버플로입니다 관련된 모든 페이스북 API 를 사용하여 자바 가상 머신 (jvm) 에. 레스트프브 를 보는 것이 좋습니다 좋은 선택입니다 라리브러리 사용할 수 있습니다.
나는, 이것은 간단한 방법으로 일을 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;
}
}
이 클래스의 객체를 json 되돌려줍니다 url 에서
이 경우, json 객체에는 다운로드하려는 방금 호출하십시오 클래스 및 이 같은 방법으로 사용자의 활동을 클래스
여기 내 코드
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"; 가 value
이렇게 하면 전달하십시오 json 값을 구체화하십시오 컨텐트입니다.
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.25.1</version>
</dependency>
이를 통해 it 호출하십시오 예:
String json = ClientBuilder.newClient().target("http://api.coindesk.com/v1/bpi/currentprice.json").request().accept(MediaType.APPLICATION_JSON).get(String.class);
그러면 Google& # 39 의 그슨 구문 분석을 위해 JSON:
Gson gson = new Gson();
Type gm = new TypeToken<CoinDeskMessage>() {}.getType();
CoinDeskMessage cdm = gson.fromJson(json, gm);