簡體   English   中英

將json URL導入java並使用jackson庫解析它

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM