Есть ли какой-либо простейший способ разобрать JSON из URL? Я использовал Gson. Я не могу найти полезные примеры.
Разбор JSON из URL
Ответ 1
-
Сначала вам нужно загрузить URL-адрес (в виде текста):
private static String readUrl(String urlString) throws Exception { BufferedReader reader = null; try { URL url = new URL(urlString); reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buffer = new StringBuffer(); int read; char[] chars = new char[1024]; while ((read = reader.read(chars)) != -1) buffer.append(chars, 0, read); return buffer.toString(); } finally { if (reader != null) reader.close(); } }
-
Затем вам нужно проанализировать его (и здесь у вас есть некоторые параметры).
-
GSON (полный пример):
static class Item { String title; String link; String description; } static class Page { String title; String link; String description; String language; List<Item> items; } public static void main(String[] args) throws Exception { String json = readUrl("http://www.javascriptkit.com/" + "dhtmltutors/javascriptkit.json"); Gson gson = new Gson(); Page page = gson.fromJson(json, Page.class); System.out.println(page.title); for (Item item : page.items) System.out.println(" " + item.title); }
Выходы:
javascriptkit.com Document Text Resizer JavaScript Reference- Keyboard/ Mouse Buttons Events Dynamically loading an external JavaScript or CSS file
-
Попробуйте API java из json.org:
try { JSONObject json = new JSONObject(readUrl("...")); String title = (String) json.get("title"); ... } catch (JSONException e) { e.printStackTrace(); }
-
Ответ 2
GSON имеет конструктор, который принимает объект Reader: fromJson (Reader json, Class classOfT).
Это означает, что вы можете создать Reader из URL, а затем передать его в Gson, чтобы использовать поток и выполнить десериализацию.
Всего три строки соответствующего кода.
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;
import com.google.gson.Gson;
public class GsonFetchNetworkJson {
public static void main(String[] ignored) throws Exception {
URL url = new URL("https://httpbin.org/get?color=red&shape=oval");
InputStreamReader reader = new InputStreamReader(url.openStream());
MyDto dto = new Gson().fromJson(reader, MyDto.class);
// using the deserialized object
System.out.println(dto.headers);
System.out.println(dto.args);
System.out.println(dto.origin);
System.out.println(dto.url);
}
private class MyDto {
Map<String, String> headers;
Map<String, String> args;
String origin;
String url;
}
}
Если вам случится получить код ошибки 403 с конечной точкой, которая в остальном работает нормально (например, с помощью
curl
или других клиентов), то возможной причиной может быть то, что конечная точка ожидает заголовокUser-Agent
и по умолчанию Java URLConnection не устанавливает его.Простое решение - добавить в начало файла, например,System.setProperty("http.agent", "Netscape 1.0");
,
Ответ 3
Вы можете использовать org.apache.commons.io.IOUtils для загрузки и org.json.JSONTokener для разбора:
JSONObject jo = (JSONObject) new JSONTokener(IOUtils.toString(new URL("http://gdata.youtube.com/feeds/api/videos/SIFL9qfmu5U?alt=json"))).nextValue();
System.out.println(jo.getString("version"));
Ответ 4
Вот простой способ.
Сначала проанализируйте JSON с url -
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
Затем поместите задачу, а затем прочитайте нужное значение из JSON -
private class ReadPlacesFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
JSONObject json;
try {
json = new JSONObject(result);
////CREATE A JSON OBJECT////
JSONObject data = json.getJSONObject("JSON OBJECT NAME");
////GET A STRING////
String title = data.getString("");
//Similarly you can get other types of data
//Replace String to the desired data type like int or boolean etc.
} catch (JSONException e1) {
e1.printStackTrace();
}
//GETTINGS DATA FROM JSON ARRAY//
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray postalCodesItems = new JSONArray(
jsonObject.getString("postalCodes"));
JSONObject postalCodesItem = postalCodesItems
.getJSONObject(1);
} catch (Exception e) {
Log.d("ReadPlacesFeedTask", e.getLocalizedMessage());
}
}
}
Затем вы можете поставить задачу следующим образом:
new ReadPlacesFeedTask()
.execute("JSON URL");
Ответ 5
public static TargetClassJson downloadPaletteJson(String url) throws IOException {
if (StringUtils.isBlank(url)) {
return null;
}
String genreJson = IOUtils.toString(new URL(url).openStream());
return new Gson().fromJson(genreJson, TargetClassJson.class);
}
Ответ 6
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.io.FileUtils;
import groovy.json.JsonSlurper;
import java.io.File;
tmpDir = "/defineYourTmpDir"
URL url = new URL("http://yourOwnURL.com/file.json");
String path = tmpDir + "/tmpRemoteJson" + ".json";
remoteJsonFile = new File(path);
remoteJsonFile.deleteOnExit();
FileUtils.copyURLToFile(url, remoteJsonFile);
String fileTMPPath = remoteJsonFile.getPath();
def inputTMPFile = new File(fileTMPPath);
remoteParsedJson = new JsonSlurper().parseText(inputTMPFile.text);
Ответ 7
Я использую java 1.8 с com.fasterxml.jackson.databind.ObjectMapper
ObjectMapper mapper = new ObjectMapper();
Integer value = mapper.readValue(new URL("your url here"), Integer.class);
Integer.class также может быть сложным. Например, используется.
Ответ 8
Используйте этот инструмент для преобразования JSON в POJO (простые старые объекты Java).
Инструмент: http://www.jsonschema2pojo.org/
Большинство ошибок только из-за неправильного отображения.
Ответ 9
Простое альтернативное решение:
-
Вставьте URL-адрес в конвертер json в csv
-
Откройте CSV файл в Excel или Open Office
-
Используйте инструменты электронной таблицы для анализа данных