xmlParser
xmlParser

Reputation: 2021

Modify JSON, using Java

Hello I have app that is generating JSON data. When i open the route /someData I can see the JSON as I want, but when I save it in file or print it in Eclipse it adds Object name before the data:

MyObjectSchema [latitude=45.95472, longitude=13.664836, Timezone=Europe, currently={time=1459936800}...]

How can i delete MyObjectSchema that is before the list. This is my code:

@Scheduled(fixedDelayString = "${fixedDelaySchema}", initialDelayString = "${initialDelaySchema}")
    public MyObjectSchema createMySchema() throws IOException {
        Map<String, ArrayList<MyObject>> map = new HashMap<String, ArrayList<MyObject>>();
        map.put("data", (ArrayList<MyObject>) list1);
        Map<String, Long> map1 = new HashMap<String, Long>();
        map1.put("time", list1.get(0).getTime());

        MyObjectSchema obj1 = new MyObjectSchema();
        obj1.setLatitude(rf.getLatitude());
        obj1.setLongitude(rf.getLongitude());
        obj1.setTimezone(rf.getTimezone());
        obj1.setCurrently(map1);
        obj1.setHourly(map);
        System.out.println(obj1);
        listSchema.add(obj1);

        if (list1.get(0).getTime() == 1460019600) {
            String jsonString = obj1.toString();
            String path = "test.json";

            ObjectOutputStream outputStream = null;
            try {
                outputStream = new ObjectOutputStream(new FileOutputStream(path));
                System.out.println("Start Writings");
                outputStream.writeObject(jsonString);
                outputStream.flush();
                outputStream.close();
                System.exit(0);
            } catch (Exception e) {
                System.err.println("Error: " + e);
            }
        }
        return obj1;
    }

Upvotes: 0

Views: 104

Answers (3)

Bambus
Bambus

Reputation: 1583

I faced with similar problem in the past. You can fix it like this:

String response = new Gson().toJson(listSchema);
 BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\Desktop\\file.json"));
      writer.write(response);
      writer.close();

Upvotes: 1

Yuvaraj Ram
Yuvaraj Ram

Reputation: 67

Use Libraries like GSON.
To use Gson, declares the following dependency.

pom.xml
<dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.6.2</version>
</dependency>

// 1. Java object to JSON, and save into a file
gson.toJson(obj1, new FileWriter("D:\\test.json"));

Upvotes: 1

Nyamiou The Galeanthrope
Nyamiou The Galeanthrope

Reputation: 1214

obj1.toString() is calling the toString() method of your object MyObjectSchema which right now doesn't generate a JSON valid string. You could modify your toString() method in order to generate proper JSON by string concatenation, but I don't recommend it. Instead use a library like Jackson or Gson to easily create JSON from your objects.

Upvotes: 2

Related Questions