0

I am trying to reformat this json file to a different format. I never used jackson or gson before. I get the idea of it but I don't know how to implement it.

So what I have is a json file: file.json that contains:

 { 
     "Fruits": [
           {
             "name": "avocado",
             "organic": true
           },
           {
              "name": "mango",
              "organic": true
           }
    ]
}

What I want is to get in this format:

    { 
       "List Fruits":{
        "Fruits": [
           {
             "name": "avocado",
             "organic": true
           },
           {
              "name": "mango",
              "organic": true
           }
        ]
      }  
   }

Somehow add the "List Fruits" in the json file.

I am trying to use the jackson api but I don't know how.

3 Answers 3

1

Assign the JSON to String variable, for example assign the above JSON to variable called json:

String json = "..." // here put your JSON text;

Prepare classes for your objects:

class Fruit {
    private String name;
    private boolean organic;
}

class Fruits {
    private List<Fruit> fruits;
}

then use Gson to convert JSON to your objects:

Gson gson = new Gson();
Fruits fruits = gson.fromJson(json, Fruits.class);

Next prepare wrapper class ListOfFruits for your fruits object:

class ListOfFruits {
    private Fruits listOfFruits;

    public ListOfFruits(Fruits fruits) {
        listOfFruits = fruits;
    }
}

Next pack your fruits object into another one:

ListOfFruits lof = new ListOfFruits(fruits);

And finally generate back the output JSON:

String newJson = gson.toJson(lof);
Sign up to request clarification or add additional context in comments.

6 Comments

I created my Fruit and Fruits classes. I am not quite sure how to use the wrapper.
It is displayed in "Next pack your fruits object into another one" section above.
Got {"listofFruits":{}}. I am doing something wrong here.
I am stuck on how this ListOffruits access the Fruit and the Fruits class. If you can kindly help I would appreciate it.
@Woods I have created a sample for you. It's a maven project. github.com/rajramo61/jsonwrapper
|
1

You do not need to create POJO model for reading and updating JSON. Using Jackson, you can read whole JSON payload to JsonNode, create a Map with required key and serialising to JSON back. See below example:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.File;
import java.util.Collections;
import java.util.Map;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        JsonNode root = mapper.readTree(jsonFile);
        Map<String, JsonNode> output = Collections.singletonMap("List Fruits", root);

        System.out.println(mapper.writeValueAsString(output));
    }
}

Above code prints:

{
  "List Fruits" : {
    "Fruits" : [ {
      "name" : "avocado",
      "organic" : true
    }, {
      "name" : "mango",
      "organic" : true
    } ]
  }
}

5 Comments

It didn't like this. It gave me an error. Exception in thread "main" java.lang.NoClassDefFoundError: com/fasterxml/jackson/annotation/JsonAutoDetect
@Woods, you need to add dependency to jackson-annotations. Do you use Maven or something similar?
Thanks. I have already solved this. I added jar files. It works. Thanks!
Is there a way to go over the entire array and find objects such as Fruits and Vegetables? I mean like the above and then when it finds Vegetables makes a list of Vegetables. I am trying this but no luck.
@Woods, this is a new problem comparing to what is asked in an original question. If my answer solves above problem, please, accept and upvote. And then ask another question and add a link to this one. It will be easier to find and answer it for other devs. If you want to work with JSON payload it is a good idea to create a POJO model which represents your JSON. After that you should be able to iterate over objects and filter or change them if needed.
0

I would highly recommend going through the documentations of Jackson or Gson libraries as you mentioned you are new. I have created a sample git repo for this item. This sample uses Jackson API.

Visit https://github.com/rajramo61/jsonwrapper

final InputStream fileData = ClassLoader.getSystemResourceAsStream("file.json");
    ObjectMapper mapper = new ObjectMapper();
    InitialJson initialJson = mapper.readValue(fileData, InitialJson.class);
    System.out.println(mapper.writeValueAsString(initialJson));
    final FinalJson finalJson = new FinalJson();
    finalJson.setListOfFruits(initialJson);
    System.out.println(mapper.writeValueAsString(finalJson));

This is the Fruit class.

public class Fruit {
private String name;
private boolean organic;

public String getName() {
    return name;
}

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

public boolean getOrganic() {
    return organic;
}

public void setOrganic(boolean organic) {
    this.organic = organic;
}

@Override
public String toString() {
    return "Fruit{" +
            "name='" + name + '\'' +
            ", organic=" + organic +
            '}';
}

}

Here is FinalJson class detail. This is the class will wrap the initial json loaded from jsn file.

public class FinalJson {
private InitialJson listOfFruits;

@JsonProperty("List Fruits")
public InitialJson getListOfFruits() {
    return listOfFruits;
}

public void setListOfFruits(InitialJson listOfFruits) {
    this.listOfFruits = listOfFruits;
}

}

Here is InitialJson class detail. This is the class pulls data from json file.

public class InitialJson {
private List<Fruit> fruits;

@JsonProperty("Fruits")
public List<Fruit> getFruits() {
    return fruits;
}

public void setFruits(List<Fruit> fruits) {
    this.fruits = fruits;
}

@Override
public String toString() {
    return "InitialJson{" +
            "fruits=" + fruits +
            '}';
}

}

You can fork the repo and close this in local and it should work fine.

7 Comments

It didn't like this. It gave me an error. Exception in thread "main" java.lang.NoClassDefFoundError: com/fasterxml/jackson/annotation/JsonAutoDetect
@Woods Did you clone the repo github.com/rajramo61/jsonwrapper and tried? It's a working example.
Yeah. Works. Thank you so much! I really appreciate it!
Is there a way to use jars without a maven project?
Then you have to download the jars and use them in your class path. You can easily setup this is your IDE. I have created a sample project for this. If you are using IDE then you need to add lib directory in your classpath to refer to the jars. github.com/rajramo61/json-wrapper-no-maven
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.