Как преобразовать получаемую строку в hasmap или arrayList в Java?
Имеется GET запрос, после всех махинаций у меня получается одна большая строка с всей информацией. Как мне ее преобразовать в что то более структурированное типа hasmap или arrayList?
package ghibli;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class Main {
public static void main(String[] args) {
try {
String url = "https://ghibliapi.herokuapp.com/films";
URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
// response.append("\n");
}
in.close();
// System.out.println(response.toString().replaceAll("^.|.$", ""));
String stringValuses = response.toString().replaceAll("^.|.$", "");
System.out.println(stringValuses);
Object objJson = JSONValue.parse(stringValuses);
// System.out.println(stringValuses);
JSONObject jsonObject = (JSONObject) objJson;
System.out.println(jsonObject);
String name = (String) jsonObject.get("title");
// System.out.println(name);
// Ghibli ghibli = new Ghibli();
// ghibli.startApp();
} catch (IOException ex) {
Logger.getLogger(Ghibli.class.getName()).log(Level.SEVERE, null, ex);
}
// ghibli.getData("https://ghibliapi.herokuapp.com/films");
}
}
Ответы (1 шт):
Автор решения: Дмитрий
→ Ссылка
Используем okhttp, gson, lombok, это все упростит. Получаем примерно следующее:
public class Main {
private final static OkHttpClient HTTP_CLIENT = new OkHttpClient();
private final static Gson GSON = new Gson();
public static void main(String[] args) throws Exception {
Request request = new Request.Builder()
.url("https://ghibliapi.herokuapp.com/films")
.get()
.build();
Response result = HTTP_CLIENT.newCall(request).execute();
List<Model> models = GSON.fromJson(result.body().charStream(), List.class);
System.out.println(models);
}
}
@Data
class Model{
public String id;
public String title;
public String original_title;
public String original_title_romanised;
public String description;
public String director;
public String producer;
public String release_date;
public String running_time;
public String rt_score;
public List<String> people;
public List<String> species;
public List<String> locations;
public List<String> vehicles;
public String url;
}