Java generate JSON from a string

Asked

Viewed 679 times

1

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

  • 3

    Post your code so we can try to help you.

  • 2

    If you’ve already done the hardest part, which is to do JSON (string), then creating the file is a piece of cake - open it for writing and write the string on it! A JSON file is a text file, and only (but I think the encoding has to be UTF-8, I’m not sure). Nothing special. (or got it wrong, and you still haven’t set up JSON?)

  • Thanks I did what you told me I took the string already with the json format and wrote a file solving the problem.

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 a dependency:

<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 simply download them and include in your project.

And the code would be something like this:
A class with 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 his 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();
}

0

I have already solved using the Filewriter class and wrote in the file the contents of the string and saved as . json solving the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.