Need to convert below JSON Object to String JAVA

json to string java
convert json file to string java
jsonobject
how to get string from json object in java
java string to json array
how to get value from json string in java
string to json java jackson
json object from json

Need to convert below JSON Object to String JAVA, getting stuck how to do with nested array. Below is the JSON object:

{
  "url": "https://www.apple.com",
  "defer_time": 5,
  "email": true,
  "mac_res": "1024x768",
  "win_res": "1366X768",
  "smart_scroll": true,
  "layout": "portrait",
  "configs": {
    "windows 10": {
      "chrome": [
        "76",
        "75"
      ],
      "firefox": [
        "67",
        "66"
      ]
    },
    "macos mojave": {
      "chrome": [
        "76",
        "75"
      ],
      "firefox": [
        "67",
        "66"
      ]
    }
  }
}

Currently, I am using JSONObject and JSONArray to write the code, but not able to get it proper for nested array.

Any help will be appreciated, many thanks !!

this code will clear everything for you i hope. first to read json file you can open it with stream, them pass stream to JSONObject directly, because it has constructor for doing such trick, or append string from file to StringBuilder, then pass stringbuilder to string to JSONObject.

 public static void main(String[] args) {
    try(BufferedReader fileReader = new BufferedReader(new FileReader("test.json"))){
        String line="";
        StringBuilder stringBuilder = new StringBuilder();
        while ((line = fileReader.readLine()) !=null){
            stringBuilder.append(line);
        }
        JSONObject jsonObject = new JSONObject(stringBuilder.toString());
        // to add single values yo your array.
        // you can do something like this
        JSONObject config = jsonObject.getJSONObject("configs");
        JSONObject macos_mojave = config.getJSONObject("macos mojave");
        JSONArray jsonArray  = macos_mojave.getJSONArray("chrome"); // this way you will reach the array
        jsonArray.put("77"); // then you can add them new values
        jsonArray.put("78");
        System.out.println(jsonArray.toList()); //will print your array content
    } catch (IOException e){
        e.printStackTrace();
    }

    JSONArray jsonArray = new JSONArray(); // this is what you call single values, it is array
    jsonArray.put(75);
    jsonArray.put(76);

    JSONObject jsonObject1 = new JSONObject();
    jsonObject1.put("Something", jsonArray);
}

you can write them back to file like this

//if you write them back to file you will see that 77 and 78 was added to chrome array (single values as you call them)
    try(FileWriter fileWriter = new FileWriter("test.json")){
        fileWriter.write(jsonObject.toString(5));
    }catch (IOException ignore){

    }

and after opening test.json file result will be next

{
 "win_res": "1366X768",
 "layout": "portrait",
 "configs": {
      "windows 10": {
           "chrome": [
                "76",
                "75"
           ],
           "firefox": [
                "67",
                "66"
           ]
      },
      "macos mojave": {
           "chrome": [
                "76",
                "75",
                "77",
                "78"
           ],
           "firefox": [
                "67",
                "66"
           ]
      }
 },
 "smart_scroll": true,
 "defer_time": 5,
 "mac_res": "1024x768",
 "url": "https://www.apple.com",
 "email": true

}

as you see 77 and 78 was appended to "chrome" JSONArray. file will not track order because behind the scenes it is using HashMap.

JSON.stringify(), How do I convert a JSON object to a string? call writeValueAsString(ObjToConvert) method by passing object we want to convert into JSON or Use GSON API: class Gson call toJson(ObjToConvert) method by passing the object we want to convert into JSON; Run to convert your Java Obj to JSON string.

Try to parse your string to the example Java object. Then call the toString method.

ObjectMapper mapper = newObjectMapper();
String jsonInString = "your string";

//JSON from String to Object
Example yourExample = mapper.readValue(jsonInString, Example.class);
yourExample.toString();



-----------------------------------com.example.Configs.java-----------------------------------

package com.example;

import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"windows 10",
"macos mojave"
})
public class Configs {

@JsonProperty("windows 10")
private Windows10 windows10;
@JsonProperty("macos mojave")
private MacosMojave macosMojave;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

@JsonProperty("windows 10")
public Windows10 getWindows10() {
return windows10;
}

@JsonProperty("windows 10")
public void setWindows10(Windows10 windows10) {
this.windows10 = windows10;
}

@JsonProperty("macos mojave")
public MacosMojave getMacosMojave() {
return macosMojave;
}

@JsonProperty("macos mojave")
public void setMacosMojave(MacosMojave macosMojave) {
this.macosMojave = macosMojave;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

@Override
public String toString() {
return new ToStringBuilder(this).append("windows10", windows10).append("macosMojave", macosMojave).append("additionalProperties", additionalProperties).toString();
}

@Override
public int hashCode() {
return new HashCodeBuilder().append(windows10).append(additionalProperties).append(macosMojave).toHashCode();
}

@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Configs) == false) {
return false;
}
Configs rhs = ((Configs) other);
return new EqualsBuilder().append(windows10, rhs.windows10).append(additionalProperties, rhs.additionalProperties).append(macosMojave, rhs.macosMojave).isEquals();
}

}
-----------------------------------com.example.Example.java-----------------------------------

package com.example;

import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"url",
"defer_time",
"email",
"mac_res",
"win_res",
"smart_scroll",
"layout",
"configs"
})
public class Example {

@JsonProperty("url")
private String url;
@JsonProperty("defer_time")
private long deferTime;
@JsonProperty("email")
private boolean email;
@JsonProperty("mac_res")
private String macRes;
@JsonProperty("win_res")
private String winRes;
@JsonProperty("smart_scroll")
private boolean smartScroll;
@JsonProperty("layout")
private String layout;
@JsonProperty("configs")
private Configs configs;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

@JsonProperty("url")
public String getUrl() {
return url;
}

@JsonProperty("url")
public void setUrl(String url) {
this.url = url;
}

@JsonProperty("defer_time")
public long getDeferTime() {
return deferTime;
}

@JsonProperty("defer_time")
public void setDeferTime(long deferTime) {
this.deferTime = deferTime;
}

@JsonProperty("email")
public boolean isEmail() {
return email;
}

@JsonProperty("email")
public void setEmail(boolean email) {
this.email = email;
}

@JsonProperty("mac_res")
public String getMacRes() {
return macRes;
}

@JsonProperty("mac_res")
public void setMacRes(String macRes) {
this.macRes = macRes;
}

@JsonProperty("win_res")
public String getWinRes() {
return winRes;
}

@JsonProperty("win_res")
public void setWinRes(String winRes) {
this.winRes = winRes;
}

@JsonProperty("smart_scroll")
public boolean isSmartScroll() {
return smartScroll;
}

@JsonProperty("smart_scroll")
public void setSmartScroll(boolean smartScroll) {
this.smartScroll = smartScroll;
}

@JsonProperty("layout")
public String getLayout() {
return layout;
}

@JsonProperty("layout")
public void setLayout(String layout) {
this.layout = layout;
}

@JsonProperty("configs")
public Configs getConfigs() {
return configs;
}

@JsonProperty("configs")
public void setConfigs(Configs configs) {
this.configs = configs;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

@Override
public String toString() {
return new ToStringBuilder(this).append("url", url).append("deferTime", deferTime).append("email", email).append("macRes", macRes).append("winRes", winRes).append("smartScroll", smartScroll).append("layout", layout).append("configs", configs).append("additionalProperties", additionalProperties).toString();
}

@Override
public int hashCode() {
return new HashCodeBuilder().append(configs).append(winRes).append(deferTime).append(email).append(additionalProperties).append(macRes).append(layout).append(smartScroll).append(url).toHashCode();
}

@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Example) == false) {
return false;
}
Example rhs = ((Example) other);
return new EqualsBuilder().append(configs, rhs.configs).append(winRes, rhs.winRes).append(deferTime, rhs.deferTime).append(email, rhs.email).append(additionalProperties, rhs.additionalProperties).append(macRes, rhs.macRes).append(layout, rhs.layout).append(smartScroll, rhs.smartScroll).append(url, rhs.url).isEquals();
}

}
-----------------------------------com.example.MacosMojave.java-----------------------------------

package com.example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"chrome",
"firefox"
})
public class MacosMojave {

@JsonProperty("chrome")
private List<String> chrome = null;
@JsonProperty("firefox")
private List<String> firefox = null;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

@JsonProperty("chrome")
public List<String> getChrome() {
return chrome;
}

@JsonProperty("chrome")
public void setChrome(List<String> chrome) {
this.chrome = chrome;
}

@JsonProperty("firefox")
public List<String> getFirefox() {
return firefox;
}

@JsonProperty("firefox")
public void setFirefox(List<String> firefox) {
this.firefox = firefox;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

@Override
public String toString() {
return new ToStringBuilder(this).append("chrome", chrome).append("firefox", firefox).append("additionalProperties", additionalProperties).toString();
}

@Override
public int hashCode() {
return new HashCodeBuilder().append(firefox).append(additionalProperties).append(chrome).toHashCode();
}

@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof MacosMojave) == false) {
return false;
}
MacosMojave rhs = ((MacosMojave) other);
return new EqualsBuilder().append(firefox, rhs.firefox).append(additionalProperties, rhs.additionalProperties).append(chrome, rhs.chrome).isEquals();
}

}
-----------------------------------com.example.Windows10.java-----------------------------------

package com.example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"chrome",
"firefox"
})
public class Windows10 {

@JsonProperty("chrome")
private List<String> chrome = null;
@JsonProperty("firefox")
private List<String> firefox = null;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

@JsonProperty("chrome")
public List<String> getChrome() {
return chrome;
}

@JsonProperty("chrome")
public void setChrome(List<String> chrome) {
this.chrome = chrome;
}

@JsonProperty("firefox")
public List<String> getFirefox() {
return firefox;
}

@JsonProperty("firefox")
public void setFirefox(List<String> firefox) {
this.firefox = firefox;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

@Override
public String toString() {
return new ToStringBuilder(this).append("chrome", chrome).append("firefox", firefox).append("additionalProperties", additionalProperties).toString();
}

@Override
public int hashCode() {
return new HashCodeBuilder().append(firefox).append(additionalProperties).append(chrome).toHashCode();
}

@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Windows10) == false) {
return false;
}
Windows10 rhs = ((Windows10) other);
return new EqualsBuilder().append(firefox, rhs.firefox).append(additionalProperties, rhs.additionalProperties).append(chrome, rhs.chrome).isEquals();
}

}

JSON.stringify(), How do you pass a JSON object into a string in Java? This page shows how to convert java object to JSON string using Google gson API. Please watch Part 18 from jQuery tutorial before proceeding. You can add doublequotes with a Jun 27, 2019 · The most common way to convert Java Object to JSON string is to use an API. It ignores all JSON notation characters and leaves just strings (and numbers, too.

Here is how you could do it with BSON

 import java.util.ArrayList;
 import org.bson.Document;

Declare all the json objects and arrays you plan to use in your code.

 Document root= new Document();
 Document rootConfigs = new Document();
 Document rootConfigsWindows10 = new Document();
 ArrayList rootConfigsWindows10Chrome= new ArrayList();
 ArrayList rootConfigsWindows10Firefox= new ArrayList();
 Document rootConfigsMacosmojave = new Document();
 ArrayList rootConfigsMacosmojaveChrome= new ArrayList();
 ArrayList rootConfigsMacosmojaveFirefox= new ArrayList();

Assign out your strings and integers to the correct JSON documents.

 root.append("url","https://www.apple.com");

 root.append("defer_time",5);

 root.append("email",true);

 root.append("mac_res","1024x768");

 root.append("win_res","1366X768");

 root.append("smart_scroll",true);

 root.append("layout","portrait");

 rootConfigsWindows10Chrome.add("76");

 rootConfigsWindows10Chrome.add("75");

 rootConfigsWindows10Firefox.add("67");

 rootConfigsWindows10Firefox.add("66");

 rootConfigsMacosmojaveChrome.add("76");

 rootConfigsMacosmojaveChrome.add("75");

 rootConfigsMacosmojaveFirefox.add("67");

 rootConfigsMacosmojaveFirefox.add("66");

Merge all the jsons together in the right order to form your nested JSON in the ROOT object

 if (!rootConfigsWindows10Chrome.isEmpty()){
 rootConfigsWindows10.append("chrome",rootConfigsWindows10Chrome);
 }
 if (!rootConfigsWindows10Firefox.isEmpty()){
 rootConfigsWindows10.append("firefox",rootConfigsWindows10Firefox);
 }
 if (!rootConfigsWindows10.isEmpty()){
 rootConfigs.append("windows 10",rootConfigsWindows10);
 }
 if (!rootConfigsMacosmojaveChrome.isEmpty()){
 rootConfigsMacosmojave.append("chrome",rootConfigsMacosmojaveChrome);
 }
 if (!rootConfigsMacosmojaveFirefox.isEmpty()){
 rootConfigsMacosmojave.append("firefox",rootConfigsMacosmojaveFirefox);
 }
 if (!rootConfigsMacosmojave.isEmpty()){
 rootConfigs.append("macos mojave",rootConfigsMacosmojave);
 }
 if (!rootConfigs.isEmpty()){
 root.append("configs",rootConfigs);
 }

Output your JSON to see if it worked.

 System.out.println(root.toJson());

How to create JSON Object using String?, What function will convert a JavaScript object to a JSON string? Jackson 2 – Convert Java Object to / from JSONjQuery loop over JSON string – $.each exampleHow to access JSON object in JavaScriptJackson : was expecting double-quote to start field name Java JSON Tutorial […]

Convert JsonObject to String, is specified or optionally including only the specified properties if a replacer array is specified. Convert Java Object to JSON using Jackson Jackson is a easy to use API that can help in the Java to/from JSON transformation. In this post lets see how to convert java object to json using Jackson.

3 ways to convert String to JSON object in Java?, There is an inbuilt method to convert a JSONObject to a String. Why don't you use that: JSONObject json = new JSONObject(); json.toString();. This produces the below output: IT Converting JSON to List of Objects. Now that we have learned how to convert json to POJO, we also should now how we can convert a json which consist of array of json to java.util.List. For example, consider the below JSON:

How can I convert String to JSON object in Java?, You can convert JSON String to Java object in just 2 lines by using Gson as shown below : Gson g = new Gson(); Player p = g.fromJson(jsonString, Player.class) JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser. parse(stringToParse); Player ronaldo = new ObjectMapper(). Converting JSON Array to Java Object when Array Elements Could Be Different Tag: java , json Could anyone offer suggestions on a JSON library or code snippet that deals with converting a JSON file such as the one below to a Java object when there could be different key-value pairs in each array element?

Comments
  • can you show the code?
  • stackoverflow.com/questions/58267787/… allmost similar quesiton, do it in reverse order, read from json file. bind values to objects and toString them in the end.
  • Try Jackson's object mapper.
  • Hey @GeorgeWeekson can you please tell, how can I add single values like 76 and 75 as shown in above JSON object? It only takes a pair value. Please suggest.
  • @Abin it is not single values. it is JSONArray, you cna create JSONArray and then add values to it. i will post code now and check it out