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();
}
Post your code so we can try to help you.
– Renan
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?)
– mgibsonbr
Thanks I did what you told me I took the string already with the json format and wrote a file solving the problem.
– gabrielguedes