Java generate JSON from a string

1

I am a beginner in programming and have never worked with json I am doing a work on and graphs and to make the graphical representation of the graph I need to generate a json with the data of the graph, I made a method that returns a string with the contents that I need in json, I would like to know how I can generate the json file from the return of this method.

    
asked by anonymous 19.11.2015 / 17:29

2 answers

1

If you have already done the method that returns a String, just put it in JSON format.

An alternative would be to generate a JSON, from an object, see below:

If you are using Maven in your project, you can include these two libraries as dependencies:

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-core</artifactId>
   <version>2.6.1</version>
</dependency>
<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.6.1</version>
</dependency>

Or just download and include them in your project.

And the code would look something like this:
A class with the attributes

public class Person{
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

And your method:

ObjectMapper mapper = new ObjectMapper();

Person person = new Person();

person.setName("Name");
person.setAge(12);

try {
      String out = mapper.writeValueAsString(person);
      System.out.println(out);
} catch (JsonProcessingException e) {
      e.printStackTrace();
}
    
20.11.2015 / 15:02
0

I have already solved the FileWriter class and wrote the contents of the string in the file and saved it as .json by solving the problem.

    
19.11.2015 / 18:08