从一个 .json 文件中获取 JSON 值。

huangapple go评论83阅读模式
英文:

Getting JSON values from a .json

问题

我目前正在编写一个程序,从openweathermaps api中获取天气信息。它返回一个类似于这样的JSON字符串:

{"coord":{"lon":-95.94,"lat":41.26},"weather":[{"id":500,"main":"Rain","description":"light 
rain","icon":"10n"}],"base":"stations","main": ...更多的json内容

我有下面这个方法,它将字符串写入一个.json文件,并允许我从中获取值。

    public String readJSON() {
		
		JSONParser parse = new JSONParser();
		String ret = "";
		
		try {
			FileReader reader = new FileReader("C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json");
			Object obj = parse.parse(reader);
			
			JSONObject Jobj = (JSONObject) obj;
			System.out.println(Jobj.get("weather"));
	
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		System.out.println(ret);
		return ret;
	}

问题在于它只允许我获取外部值,如"coord""weather"。因此,当前由于我有System.out.println(Jobj.get("weather"));,它将返回[{"icon":"10n","description":"light rain","main":"Rain","id":500}],但我实际上想要获取其中的值,如description值和main值。我在处理JSON方面的经验不多,所以可能有一些明显的东西我漏掉了。你对如何实现这一点有什么想法吗?

英文:

I am currently writing a program that pulls weather info from openweathermaps api. It returns a JSON string such as this:

{"coord":{"lon":-95.94,"lat":41.26},"weather":[{"id":500,"main":"Rain","description":"light 
rain","icon":"10n"}],"base":"stations","main": ...more json

I have this method below which writes the string to a .json and allows me to get the values from it.

	public String readJSON() {
	
	JSONParser parse = new JSONParser();
	String ret = "";
	
	try {
		FileReader reader = new FileReader("C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json");
		Object obj = parse.parse(reader);
		
		JSONObject Jobj = (JSONObject) obj;
		System.out.println(Jobj.get("weather"));

	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} catch (ParseException e) {
		e.printStackTrace();
	}
	System.out.println(ret);
	return ret;

}

The problem is it only allows me to get the outer values such as "coord" and "weather". So currently since I have System.out.println(Jobj.get("weather")); it will return [{"icon":"10n","description":"light rain","main":"Rain","id":500}] but I want to actually get the values that are inside of that like the description value and the main value. I haven't worked much with JSONs so there may be something obvious I am missing. Any ideas on how I would do this?

答案1

得分: 1

你可以使用 JsonPath(https://github.com/json-path/JsonPath)来直接提取一些 JSON 字段/值。

 var json = "{
   \"coord\":{\"lon\":\"-95.94\",\"lat\":\"41.26\"},
   \"weather\":[{\"id\":\"500\",\"main\":\"Rain\",\"description\":\"light\"}]
 }";
 var main = JsonPath.read(json, "$.weather[0].main");  // Rain
英文:

You can use JsonPath (https://github.com/json-path/JsonPath) to extract some json field/values directly.

 var json = "{\"coord\":{\"lon\":\"-95.94\",\"lat\":\"41.26\"},\n" +
                " \"weather\":[{\"id\":\"500\",\"main\":\"Rain\",\"description\":\"light\"}]}";
 var main = JsonPath.read(json, "$.weather[0].main");  // Rain

答案2

得分: 1

你可以使用以下代码:

JSONObject Jobj = (JSONObject) obj;
System.out.println(Jobj.getJSONObject("coord").get("lon")); // 这里的 coord 是 JSON 对象
System.out.println(Jobj.getJSONArray("weather").getJSONObject(0).get("description")); // 对于数组

或者你可以根据结构声明用户定义的类并使用 GSON 进行代码转换

Gson gson = new Gson();
MyWeatherClass weather = gson.fromJson(Jobj.toString(), MyWeatherClass.class);
System.out.println(weather.getCoord());
英文:

you can use

JSONObject Jobj = (JSONObject) obj;
System.out.println(Jobj.getJSONObject("coord").get("lon");//here coord is json object
System.out.println(Jobj.getJSONArray("weather").get(0).get("description");//for array

or you can declare user defined class according to structure and convert code using GSON

Gson gson= new Gson();
MyWeatherClass weather= gson.fromJSON(Jobj .toString(),MyWeatherClass.class);
System.out.println(weather.getCoord());

答案3

得分: 0

根据您提供的 JSON 示例,可以看出 "weather" 实际上是一个对象数组,因此在代码中需要将其视为数组,以便在转换为 JsonObject 后从数组中获取各个对象。
可以尝试类似以下的代码:

public String readJSON() {

    JSONParser parse = new JSONParser();
    String ret = "";

    try {
        FileReader reader = new FileReader("C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json");
        Object obj = parse.parse(reader);

        JSONObject jobj = (JSONObject) obj;
        JSONArray jobjWeatherArray = jobj.getJSONArray("weather");
        
        for (int i = 0; i < jobjWeatherArray.length(); i++) {
            JSONObject jobjWeather = jobjWeatherArray.getJSONObject(i);
            System.out.println(jobjWeather.get("id"));
            System.out.println(jobjWeather.get("main"));
            System.out.println(jobjWeather.get("description"));
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    System.out.println(ret);
    return ret;

}
英文:

From the json sample that you have provided it can be seen that the "weather" actually is an array of objects, so you will have to treat it as such in code to get individual objects from the array when converted to Jsonobject.
Try something like :

public String readJSON() {

JSONParser parse = new JSONParser();
String ret = &quot;&quot;;

try {
    FileReader reader = new FileReader(&quot;C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json&quot;);
    Object obj = parse.parse(reader);

    JSONObject jobj = (JSONObject) obj;
    JSONArray jobjWeatherArray = jobj.getJSONArray(&quot;weather&quot;)
    
    for (int i = 0; i &lt; jobjWeatherArray.length(); i++) {
      JSONObject jobjWeather = jobjWeatherArray.getJSONObject(i);
      System.out.println(jobjWeather.get(&quot;id&quot;));
      System.out.println(jobjWeather.get(&quot;main&quot;));
      System.out.println(jobjWeather.get(&quot;description&quot;));
    }

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (ParseException e) {
    e.printStackTrace();
}
System.out.println(ret);
return ret;

}

huangapple
  • 本文由 发表于 2020年5月5日 13:42:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/61606487.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定