Reformat JSON arrays/object in java

json array in java
read json array in java
json array of objects
how to get values from json array in java
how to parse json object in java
how to get value from json object in java example
create json object in java
how to print json object in java

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.

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);

Json array of objects, JSON is text format, and we can convert any JavaScript object into a JSON still read and parse its content to a list of Java Objects, as shown below:JSON can� To convert the JSON array into an equivalent Java array, you should do the following: User[] users = new Gson().fromJson(json, User[].class); If your JSON array is stored in a JSON file, you can still read and parse its content to a list of Java Objects using Gson, as shown below:

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
    } ]
  }
}

How to Write/create a JSON array using Java?, { "books": [ Java, JavaFX, Hbase, Cassandra, WebGL, JOGL] }. The json-simple is a light weight library which is used to process JSON objects. JSON Array for beginners and professionals with examples of JSON with java, json array of string, json array of numbers, json array of booleans, json srray of objects, json multidimentional array. Learn JSON array example with object, array, schema, encode, decode, file, date etc.

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.

Creating a JSON String from JSON Object and JSON Arrays in , Creating a JSON String from JSON Object and JSON Arrays in Automation Scripts. I needed to send a JSON formatted text as the body of an http POST request. Automation Script button) from com.ibm.json.java import JSONObject from sys� JSON Array to Java objects. Ask Question Asked 5 years, 6 months ago. Active 5 years ago. Viewed 31k times 15. I need to parse a json file wich looks like this:

How to Parse JSON in Java, JSON stands for JavaScript Object Notation, and it is based on As a data- exchange format, it is widely used in web programming. Here we show how to parse A JSON array is an ordered collection of values. The values� Parse JSON array as member Gson parses JSON arrays as members without difficulty if they are non-root objects. We can use the fromJson () method in usual manner and it will parse the json array correctly to required java array or list.

Reading and Writing JSON in Java, JSON is a generic data format that has six data types: Strings; Numbers; Booleans; Arrays; Objects; null. Let's take a look at a simple JSON document: { " name":� Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.

How to Convert JSON array to String array in Java , Java programming tutorial to convert JSON array to String array with to our last article in JSON about How to convert JSON object to Java object, use GSON to parse JSON data format and create Java String array or List� In JSON, they take on these forms: An object is an unordered set of name/value pairs. An object begins with {left brace and ends with }right brace. Each name is followed by :colon and the name/value pairs are separated by ,comma. An array is an ordered collection of values. An array begins with [left bracket and ends with ]right bracket.

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
  • 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.
  • 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