需要将下面的JSON对象转换为String JAVA

时间:2019-10-07 16:05:42

标签: java arrays json jsonschema

需要将下面的JSON对象转换为String JAVA,陷入如何处理嵌套数组的困境。下面是JSON对象:

 {
  "ar": {
    "key1": "Ap",
    "key2": "ap2"
  },
  "en": {
    "key1": "Ap",
    "key2": "ap2"
  }
}

当前,我正在使用JSONObject和JSONArray编写代码,但无法使其正确用于嵌套数组。

任何帮助将不胜感激,谢谢!!

3 个答案:

答案 0 :(得分:0)

此代码将为您清除所有内容。首先阅读json文件,您可以使用流打开它,它们直接将流传递给JSONObject,因为它具有执行此技巧的构造函数,或者将文件中的字符串附加到StringBuilder,然后将stringbuilder传递给string到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);
}

您可以像这样将它们写回到文件中

//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){

    }

打开test.json文件后,结果将是下一个

{
 "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

}

如您所见,

77和78被附加到“ chrome” JSONArray。文件将不会跟踪顺序,因为在后台它正在使用HashMap。

答案 1 :(得分:0)

尝试将您的字符串解析为示例Java对象。然后调用toString方法。

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

}

答案 2 :(得分:0)

在这里,您可以使用BSON做到这一点

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

声明您计划在代码中使用的所有json对象和数组。

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

将您的字符串和整数分配给正确的JSON文档。

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

以正确的顺序将所有json合并在一起,以在ROOT对象中形成嵌套的JSON

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

输出您的JSON以查看它是否有效。

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