How to read json file into java with jackson library?

4.8k views Asked by At

I want to read this simple JSONfile with java jackson library(I'm new to JSON).

Coud you please tell to me what i do wrong?I created class or JSON object wrongly or this metod of convertion JSON object to Java is wrong, thanks

Edit now i get set of exception like this

enter image description here

This is what the JSONfile stores

 {
      "id": 15,
      "name": "Steve",
      "Datax": {
        "veek": "vect",
        "seev": "vecs"
      }
    }

And i have three classes

Here is a Cevan:

public class Cevan {
    private int id;
    private String name;
    private Datax data;

    public Datax getData() {
        return data;
    }

    public void setData(Datax data) {
        this.data = data;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }
}

and Datax:

public class Datax {
    private String veek;
    private String seev;

    public String getSeev() {
        return seev;
    }

    public String getVeek() {
        return veek;
    }

    public void setSeev(String seev) {
        this.seev = seev;
    }

    public void setVeek(String veek) {
        this.veek = veek;
    }
}

and Class Main:

     public class Main {
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper=new ObjectMapper();
        InputStream is= Cevan.class.getClassLoader().getResourceAsStream("json2.json");
        Cevan testObj = mapper.readValue(is, Cevan.class);


    }
}

It's like my project looks

2

There are 2 answers

0
garfield On BEST ANSWER

It should be nice to have the log files attached as text and not as image.

The problem should be in the json file.

According to your java classes the json file should be as follows:

 {
  "id": 15,
  "name": "Steve",
  "data": {
    "veek": "vect",
    "seev": "vecs"
  }
}

Note the object attribute change from "Datax" to "data".

3
Dmitrii B On

Change your resourseStreamReader from

InputStream is=Cevan.class.getResourceAsStream("json2.json");

to:

InputStream is = this.getClassLoader().getResourceAsStream("json2.json");

and also make sure what your json2.json is in classpath