我有一个像这样的JSON结构:
{
"text" : "MVA/Transport. Greater Hume (Hume Hwy, Holbrook, NSW 2644) at 7 Mar 2017 03:58 #NSWRFS #MVATransport",
"user" : {
"id" : "4721717942",
"name" : "NSW Fire Updates"
},
"lang" : "en",
"coordinates" : {
"coordinates" : [147.273696, -35.785469],
"type" : "Point"
},
"created_at" : "Mon Mar 06 17:29:31 +0000 2017"
}
我在解析coordinates
对象中的coordinates
数组时遇到问题。
public class ParsingTweet {
public static void main(String[] args) throws IOException {
assert args != null & args.length > 0;
List<Tweet> tweets = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();
try (BufferedReader reader = new BufferedReader(new FileReader("tweets.json"))) {
String line;
while ((line = reader.readLine()) != null) {
tweets.add(mapper.readValue(line, Tweet.class));
}
}
System.out.println(tweets);
}
}
其中coordinates
打印为:
coordinates = ClassPojo [type = Point, coordinates = [Ljava.lang.Double;@1810399e]]
而不是:
coordinates = ClassPojo [type = Point, coordinates = [147.273696, -35.785469]]
以下是我的POJO:
@JsonIgnoreProperties(ignoreUnknown = true)
public class Tweet {
private String text;
private String created_at;
private User user;
private Coordinates coordinates;
public Tweet(){
}
public String getText()
{
return text;
}
public void setText(String text)
{
this.text = text;
}
public String getCreated_at()
{
return created_at;
}
public void setCreated_at(String created_at)
{
this.created_at = created_at;
}
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
public Coordinates getCoordinates()
{
return coordinates;
}
public void setCoordinates(Coordinates coordinates)
{
this.coordinates = coordinates;
}
@Override
public String toString()
{
return "[text = "+text+", created_at = "+created_at+", user = "+user+", coordinates = "+coordinates+"]";
}
}
public class Coordinates {
private String type;
private String[] coordinates;
public String getType ()
{
return type;
}
public void setType (String type)
{
this.type = type;
}
public String[] getCoordinates()
{
return coordinates;
}
public void setCoordinates (String[] coordinates)
{
this.coordinates = coordinates;
}
@Override
public String toString()
{
return "ClassPojo [type = "+type+", coordinates = "+coordinates+"]";
}
}
答案 0 :(得分:0)
可以尝试在String[]
中从List<String>
更改为Coordinate
。
它看起来像Double[]
一样?虽然我不明白为什么,因为您的Coordinate
课程有String[]
字段。
考虑一下你是否拥有1个值或2个以上值的JSON数组 - 即使它们不是有效的坐标,解析器也会很乐意将其解析为Java List或数组。
如果您的double[]
POJO具有String[]
,那么它不会解析为List<String>
,Coordinate
或double latitude
,而是更好和double longitude
作为属性。您可以使用JSON解析库执行此操作,或者您可以将其视为API模型的第一个转换解析,然后再将其转换为您的域模型。
答案 1 :(得分:0)
您正在打印数组...所以您需要正确地执行此操作
@Override
public String toString()
{
return + Coordinates.class.getSimpleName()
+ " [type = " + type
+ ", coordinates = " + Arrays.toString(coordinates)
+ "]";
}