java 将 JSON 文件转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37001421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:05:54  来源:igfitidea点击:

Convert JSON file to String

javajsonparsing

提问by lars

I am pretty new to Java and have an issue that I don't know how to fix. I read a few tutorials, posted questions etc. but I was still not able to understand how to Transfer the knowledge Fixing my Problem.

我对 Java 很陌生,但有一个我不知道如何解决的问题。我阅读了一些教程,发布了问题等,但我仍然无法理解如何转移解决我的问题的知识。

Here to Problem.

问题来了。

I want to read multiple json files all at one place and convert the data to Strings. I am able to read one data entry in the json, but not more. :-|

我想在一个地方读取多个 json 文件并将数据转换为字符串。我能够读取 json 中的一个数据条目,但不能读取更多。:-|

The file data Looks as follows:

文件数据如下:

{
    "Header":{
        "Liste1": {
            "ID": "12345",
            "Name" : "customerlist",
            "Company List": [
                "Company": "c1",
                "Company": "c2",
                "Company": "c3"
            ]
        },
        "Liste2":{
            "ID": "12346",
            "Name" : "vendorlist",
            "Company List": [
                "Company": "c4",
                "Company": "c5",
                "Company": "c6"
            ]
        }
    }
}

The code I used Main:

我使用的代码主要:

package testpaket;

import com.google.gson.Gson;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class test6 {

    public static void main(String[] args) {

        Gson gson = new Gson();

        try (Reader reader = new FileReader("test.json")) {

            // Convert JSON to Java Object
            Header header = gson.fromJson(reader, Header.class);
            System.out.println(header);

            // Convert JSON to JsonElement, and later to String
            /*JsonElement json = gson.fromJson(reader, JsonElement.class);
            String jsonInString = gson.toJson(json);
            System.out.println(jsonInString);*/



        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

My Lists class.

我的列表类。

package testpaket;

import java.util.List;

public class Lists {

    private String List;
    private int ID;
    private String Name;
    private List<String> companyList;

}

My Header class.

我的标题类。

package testpaket;

import java.util.Map;

public class Header {

        String name;
        String list;
        int id;
        String header1;


        private Map<String, Lists> header;


        //getters&setters
        public String getHeader() { 
              return this.header1; 
        }
        public void setHeader(String header) { 
            this.header1 = header1; 
        }
        public String getList() { 
              return this.list; 
        }
        public void setList(String list) { 
            this.list = list; 
        }
        public String getName() { 
              return this.name; 
        }
        public void setName(String name) { 
            this.name = name; 
        }
        public int getID() { 
              return this.id; 
        }
        public void setID(int id) { 
            this.id = id; 
        }
}

Does any of that even make sense? Sorry, but I really tried transfering the knowledge I have so far. Could anyone please help me and tell me how to fix it?

任何这些甚至有意义吗?对不起,但我真的尝试转移我到目前为止所拥有的知识。谁能帮助我并告诉我如何解决它?

采纳答案by lars

Here the complete solution using GSON:

这是使用 GSON 的完整解决方案:

package jsonProcessing;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonHeader {

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub  
    BufferedReader reader = null;

    try{
        reader = new BufferedReader(new FileReader("C:/JSON/header.json"));
        Gson gson = new GsonBuilder().create();
        HeaderResult results = gson.fromJson(reader, HeaderResult.class);

        if(results != null){
            for(Header h : results.getHeader()){
                String temp =("ID: "+h.getID()+" Name: "+h.getName());
                for(CompanyList cl : h.getCompanyList()){
                    System.out.println(temp+" "+"Company: "+cl.getCompany());
                }
            }
        }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(reader != null){
                try{
                    reader.close();
                }catch(Exception e){
                    e.printStackTrace();
                }

            }
        }
}
}

package jsonProcessing;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class HeaderResult {

@SerializedName("Header")
@Expose
private List<Header> header = null;

public List<Header> getHeader() {
return header;
}

public void setHeader(List<Header> header) {
this.header = header;
}
}

package jsonProcessing;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Header {

@SerializedName("ID")
@Expose
private String iD;
@SerializedName("Name")
@Expose
private String name;
@SerializedName("Company List")
@Expose
private List<CompanyList> companyList = null;

public String getID() {
return iD;
}

public void setID(String iD) {
this.iD = iD;
}

public String getName() {
return name;
}

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

public List<CompanyList> getCompanyList() {
return companyList;
}

public void setCompanyList(List<CompanyList> companyList) {
this.companyList = companyList;
}
}

package jsonProcessing;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class CompanyList {

@SerializedName("Company")
@Expose
private String company;

public String getCompany() {
return company;
}

public void setCompany(String company) {
this.company = company;
}
}

Finally the output:

最后输出:

ID: 12345 Name: customerlist Company: c1
ID: 12346 Name: vendorlist Company: c6

回答by salvatore rinaudo

If you want to convert JSON-files to strings, it is not necessary to convert the file to a Java Object and after to a String. With apache commons-iolibrary you can do this with only1 line.

如果要将 JSON 文件转换为字符串,则无需将文件转换为 Java 对象,然后再转换为字符串。使用 apache commons-io库,您只需1 行即可完成此操作。

String exampleRequest = FileUtils.readFileToString(new File("exampleJsonRequest.json"), StandardCharsets.UTF_8);

回答by kolakao

First of all the objects do not match the json. The Header object should contain two fields like Liste1 and Liste2 (probably of the same type). These on the other hand should contain id, name and companyList fields. Also, did you create the json? the Liste1 and Liste2 should probably be the part of collection in the json, inside the "[]" brackets, then instead of heaving two fields like Liste1 and Liste2 you could have Collection in Header object.

首先,对象与 json 不匹配。Header 对象应该包含两个字段,如 Liste1 和 Liste2(可能是相同类型)。另一方面,这些应该包含 id、name 和 companyList 字段。另外,你创建了json吗?Liste1 和 Liste2 可能应该是 json 中集合的一部分,在“[]”括号内,然后你可以在 Header 对象中拥有 Collection ,而不是像 Liste1 和 Liste2 这样的两个字段。