Utilize the Jackson library in Java to import a JSON URL and parse its contents

I am currently attempting to read and parse a JSON link using Java in order to utilize it for various purposes. However, I am encountering errors that are leaving me uncertain on how to proceed. Below is the snippet of code I am working with:

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);
    }

}

There are several errors occurring: Regarding import weather.data:Multiple markers at this line - Only a type can be imported. weather.data resolves to a package - The import weather.data is never used

Concerning City = mapper.readValue(jsonUrl, data.class):Multiple markers at this line - data cannot be resolved to a type - City cannot be resolved to a variable - The method readValue(JsonParser, Class) in the type ObjectMapper is not applicable for the arguments (URI, Class) - The method readValue(JsonParser, Class) in the type ObjectMapper is not applicable for the arguments (URI, Class) - City cannot be resolved to a variable - data cannot be resolved to a type

Any insights or suggestions? Additionally, I am struggling to grasp the concept of using mapper.readValue. Would anyone be able to provide assistance?

Note: I have utilized json gen to generate the data objects within the link, resulting in object data Java files: City, Coord, List1, Temp, and Weather with specific contents.

As an illustration, here is a sample content of 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;
    }
}

Thank you for any assistance provided in advance.

Answer №1

Instead of importing the entire package weather.data, you should import the specific class City.

Follow @jdiver's suggestion:

City city = mapper.readValue(jsonUrl, City.class);

Answer №2

When the gistfile1.txt file within the URL contains a JSON object for City, you need to update the line

City = mapper.readValue(jsonUrl, data.class);

to

City = mapper.readValue(jsonUrl, City.class);

Provide the appropriate object class to the readValue method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The jQuery call to a web service is returning XML data, but the success function is receiving a

I have utilized: [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)] The outcome of my web service call is: <string xmlns="http://tempuri.org/"> [{_pkId:"",_code:"",_message:"The file has been uploaded successfully.",_sta ...

Announcing the outcomes I received from JSON notifications

Hey there, I need some assistance. Here's the deal - whenever a user enters something into a text field and then clicks out of it, an ajax request is triggered. $(document).ready(function() { //On Focus lose get content of the first input field $(&ap ...

How to implement AJAX to call a servlet from a PHP page

I'm currently attempting to receive a response from a servlet page and display an alert on success. However, I keep encountering errors every time. I can't seem to pinpoint the issue. Here's my AJAX code: $(document).ready(function() { $ ...

Retrieving a single value from the response entity JSON data

I am in need of connecting to a rest service in order to retrieve the user id using a token. List<Object> providers = new ArrayList<>(); providers.add(new JacksonJaxbJsonProvider()); client = WebClient.create(properties.getProperty(URL), prov ...

Tips for transferring data via ajax to rails 3. The jQuery function is ensuring the string is properly handled

I am attempting to achieve the following: $.ajax({ type: "PUT", url: /example, data: {_method: "put", "foo_model[bar_attribute]": value_var } }); It is working as expected, but I need to dynamically construct the part foo_model[bar_attribute]. ...

An efficient method for extracting data from a JSON array and integrating it into a DataTables display

I am struggling to populate data tables with values from a PHP file that returns JSON responses. Despite receiving the JSON response, I am unable to successfully append the data to the data table. Below is the code snippet used for generating the JSON resp ...

Sort ActiveRecord objects based on JSON type data structure

Recently delving into the world of JSON datatypes and curious if Rails has any clever shortcuts for sorting. Let's say I have the following: object_a.payload = { "category_1" => 2, "category_2" => 1 } object_b.payload = { "category_1" => 1 } ...

code reading json without specified key

I'm facing what seems like a simple question, but I can't seem to crack the code. I'm currently coding in Python 3.3 and have retrieved something from a JSON file that resembles this: some_list = json_response['key'] # some_list ...

Auto-fill Textbox from a different Textbox in MVC 4

I am attempting to automatically fill in a textbox based on the value of another textbox, but I am struggling with getting the other textbox to populate. Below is my code - any advice on the best solution would be greatly appreciated. Action Method: [Htt ...

Reorganize the JSON data to match the specified format

{ "EUR": { "Description": "", "Bid": "1.1222", "Region": "", "Bid1": "1.1283", "CurrencyCode": "EUR", "FeedSource": "1", "Ask": "1.1226", "ProviderName": "TEST 1", "Low": "1.1195", ...

A tool designed to create a function that can fetch information from a JSON file

Currently, I am working on a function that accepts arguments and combines them to form a line for searching data in a JSON file. To accomplish this, I have initialized a variable for the readFileSync and then added the function's arguments to it in or ...

What is the process for adding an additional level to an Object for an item that is not predefined?

The primary concern at hand is as follows: Retrieve JSON data from the server Populate a form with the data Serialize the form Create a JSON object with the correct structure Send the JSON object back to the server I am facing challenges specifically on ...

Unexpected value detected in D3 for translate function, refusing to accept variable

I'm experiencing a peculiar issue with D3 where it refuses to accept my JSON data when referenced by a variable, but oddly enough, if I print the data to the console and manually paste it back into the same variable, it works perfectly fine. The foll ...

Using Selenium with Java allows for the seamless passing of a Browser instance to another method

Currently, I am in the process of automating a web task using Selenium and Java. As a beginner in both Java and Selenium, I have encountered an issue with passing a Browser instance to a called method. My main method opens a webpage, performs some tasks on ...

Analyzing information with Python's request module

I am currently facing an issue while attempting to run a query using an API to retrieve specific information. The problem I encounter is that the data retrieved is excessive. My goal is to extract only a particular value, specifically the number following ...

Utilizing JSON with ASP.NET WebForms

Is it recommended to use JSON, JQuery & ASP.NET 2.0 webforms together or is it better suited for MVC with ASP.NET 3.5 & 4.0? When incorporating JSON, should I utilize gridviews and repeaters controls for binding JSON data or should I create custom tables f ...

retrieve the result following an ajax request

In my project using spring-mvc, I have an ajax call that returns void as it only updates database data. However, if the user is not logged in, I want to redirect them to a login page. The issue is that for redirection, I need to specify String as return ...

Using JSON in Visual Basic 2010 to Encode and Decode Objects

Here is a snippet of code I have: Imports Newtonsoft.Json Imports Newtonsoft.Json.Linq Module Module1 Structure JSONList Dim Name, Email As String Dim Age As Integer End Structure Sub Main() Dim Data(1) As JSONList Data(0).Name = "Josh" ...

Finding HTML source with regular expressions in Python: A guide

I've been wracking my brain trying to crack this problem. Although the numbers and names in this scenario are made up, the concept is the same. For instance, when I go to a link like 'https://graph.facebook.com/123' This is what I get bac ...

Objective C - Organize JSON data into groups

I will attempt to explain my idea and what I hope to achieve. Here is the JSON structure: { "objects": [ { "title": "Title #1", "date": "1446930000" }, { "title": "Title #2", "date": "1437782400" }, { " ...