Newer
Older
CosmosServer / src / test / java / HttpUrlConnectionTest / SampleTest.java
package HttpUrlConnectionTest;

import com.example.cosmos_serversb.models.Groups;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import jdk.nashorn.internal.ir.ObjectNode;

import java.io.*;
import java.net.*;

public class SampleTest {
    public static String getResult(String urlString) {
        String result = "";
        try {
            URL url = new URL(urlString);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.connect();
            String tmp = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            while ((tmp = in.readLine()) != null) {
                result += tmp;
            }
            in.close();
            con.disconnect();
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public static JsonNode getJsonNode(String jsonString){
        JsonNode head = null;
        try{
            JsonFactory jfactory = new JsonFactory();
            JsonParser parser = jfactory.createJsonParser(jsonString);
            ObjectMapper mapper = new ObjectMapper();
            head = mapper.readTree(parser);
        }catch(Exception e){
            e.printStackTrace();
        }
        return head;
    }

    public static void main(String[] args) {
        String Result;
        JsonNode json;
        String URL = "https://map.yahooapis.jp/search/local/V1/localSearch?bbox=139.727685,35.663782,139.734251,35.669378&gc=02&results=20&output=json&appid=dj00aiZpPTVzYzloUDJjS0VMSyZzPWNvbnN1bWVyc2VjcmV0Jng9MGE-";
        Result = getResult(URL);
        json = getJsonNode(Result);

        String genre = json.get("Feature").get(0).get("Property").get("Genre").get(0).get("Name").asText();
        String code = json.get("Feature").get(0).get("Property").get("Genre").get(0).get("Code").asText();
        String location = json.get("Feature").get(0).get("Geometry").get("Coordinates").asText();

        String[] split = location.split(",");
        System.out.println(genre);
        System.out.println(Integer.parseInt(code));
        System.out.println(split[0]);
        System.out.println(split[1]);
        System.out.println(json);
    }
}