[英]Import json URL to java and parse it using jackson library
我试图在java中读取json链接并解析它以便我可以将它用于其他事项,但问题是我得到的错误我真的不知道如何处理它们。 这是代码:
package weather.data;
import weather.data;
import com.fasterxml.jackson.core.JsonParseException;
//import com.fasterxml.jackson.annotation.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonMappingException;
import java.io.File;
import java.net.URI;
import java.io.IOException;
public class usertest {
public static void main() throws JsonParseException, JsonMappingException, IOException
{
URI jsonUrl = new URI("https://gist.githubusercontent.com/anonymous/4b32c7ef1ceb5dd48bf5/raw/ef1987551faa3fb61473bb0e7aad70a228dc36d6/gistfile1.txt");
ObjectMapper mapper = new ObjectMapper();
City = mapper.readValue(jsonUrl, data.class);
}
}
以下是错误:关于import weather.data:此行的多个标记 - 只能导入一个类型。 weather.data解析为一个包 - 从不使用import weather.data
about City = mapper.readValue(jsonUrl,data.class):此行的多个标记 - 数据无法解析为类型 - City无法解析为变量 - ObjectMapper类型中的方法readValue(JsonParser,Class)不是适用于参数(URI,Class) - ObjectMapper类型中的方法readValue(JsonParser,Class)不适用于参数(URI,Class) - City无法解析为变量 - 数据无法解析为类型
有任何想法吗? 另外,我真的不明白使用mapper.readValue的概念。 请问有人帮我吗?
注意:我已经使用json gen生成链接内的数据对象,现在我有对象数据java文件:City,Coord,List1,Temp和Weather,内容如下。
对于City.java作为示例:
package weather.data;
import java.util.List;
public class City{
private Coord coord;
private String country;
private Number id;
private String name;
private Number population;
public Coord getCoord(){
return this.coord;
}
public void setCoord(Coord coord){
this.coord = coord;
}
public String getCountry(){
return this.country;
}
public void setCountry(String country){
this.country = country;
}
public Number getId(){
return this.id;
}
public void setId(Number id){
this.id = id;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public Number getPopulation(){
return this.population;
}
public void setPopulation(Number population){
this.population = population;
}
}
提前致谢
您需要import weather.data.City
(特定类)而不是import weather.data
(包)。
然后像@jdiver那样说:
City city = mapper.readValue(jsonUrl, City.class);
如果URL中的gistfile1.txt
文件包含City的JSON对象,则替换该行
City = mapper.readValue(jsonUrl, data.class);
同
City = mapper.readValue(jsonUrl, City.class);
您应该将对象类赋予readValue
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.