如何使用GSON库将自由文本转换为Java中的Json String Array?

时间:2015-11-16 09:46:25

标签: java json gson

我在文件中有自由文本。 我把它转换成json字符串数组时被困住了

列名称是可变的,可以是n个列

email_from,email_to,DATE_CHANGED

samwilliams@gmail.com, mike_haley@gmail.com, 1447666867

smithpaul@gmail.com, angierussell@gmail.com, 1447668867

第一行是标题,其余所有行都是它们的值。 因此,每一行都包含与每列相同数量的参数。 列以逗号分隔。

json字符串响应应该看起来像这样

{
 "data": [
    {
        "email_from": "samwilliams@gmail.com",
        "email_to": "mike_haley@gmail.com",
        "DATE_CHANGED": "1447666867"
    },
    {
        "email_from": "smithpaul@gmail.com",
        "email_to": "angierussell@gmail.com",
        "DATE_CHANGED": "1447668867"
    }
 ]
}

3 个答案:

答案 0 :(得分:2)

以下代码打开一个带逗号分隔字符串的文件,并使用while循环构造JsonObject,然后继续将它们添加到JsonArray并最终打印它(请添加您的验证,您可以将大部分代码移出try阻止,如果你想让代码表现更好)。

它解决了在文件中包含n个列的需要。

package gjson;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class GJSONTest {
    public static void main(String[] args) {

        // create an array called datasets
        JsonArray datasets = new JsonArray();

        File file = new File("C:\\test_stackoverflow\\list.txt");

        try (BufferedReader br = new BufferedReader(new FileReader(file)))  {
            String line;
            boolean flag = true; 
            List<String> columns = null; 
            while ((line = br.readLine()) != null) {
               if (flag) {
                   flag = false; 
                   //process header 
                   columns = Arrays.asList(line.split(","));
               } else {
                   //to store the object temporarily
                   JsonObject obj = new JsonObject(); 
                   List<String> chunks = Arrays.asList(line.split(","));

                   for(int i = 0; i < columns.size(); i++) {
                       obj.addProperty(columns.get(i), chunks.get(i));
                   }
                   datasets.add(obj); 
               } 
            }
        } catch(FileNotFoundException fnfe) {
            System.out.println("File not found.");
        } catch(IOException io) {
            System.out.println("Cannot read file.");
        }

        Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
        System.out.println(gson.toJson(datasets));
    }
}

请参阅以下屏幕截图(下面有3列)

enter image description here

在文本文件中添加了另一列,以下是输出。

enter image description here

以下是包含数据的示例.txt文件

enter image description here

答案 1 :(得分:1)

试试这段代码:

public class ContactObject {
    private String emailFrom;
    private String emailTo;
    private String dateChanged;

    public ContactObject(String emailFrom, String emailTo, String dateChanged) {
        this.emailFrom = emailFrom;
        this.emailTo = emailTo;
        this.dateChanged = dateChanged;
    }

    @Override
    public String toString() {
        return "{email_from:" + emailFrom + ", email_to:" + emailTo + ", DATE_CHANGED:" + dateChanged;
    }
}

public class ContactJSON {
    private List<ContactObject> data;

    public ContactJSON(List<ContactObject> contactList) {
        this.data = contactList;
    }
}

然后在main()方法中,您可以使用这些类:

public static void main(String[] args) {
    List<ContactObject> contactList = new ArrayList<ContactObject>();
    ContactObject obj1 = new ContactObject("samwilliams@gmail.com", "mike_haley@gmail.com", "1447666867");
    ContactObject obj2 = new ContactObject("smithpaul@gmail.com", "angierussell@gmail.com", "1447668867");
    contactList.add(obj1);
    contactList.add(obj2);

    Gson gson = new Gson();
    String json = gson.toJson(new ContactJSON(contactList));
    System.out.println(json);
}

<强>输出:

{"data":[{"emailFrom":"samwilliams@gmail.com","emailTo":"mike_haley@gmail.com","dateChanged":"1447666867"},{"emailFrom":"smithpaul@gmail.com","emailTo":"angierussell@gmail.com","dateChanged":"1447668867"}]}

答案 2 :(得分:1)

private String getParsedData(String data){

    String[] lines = data.split("\\r?\\n");

    List<Map> dataList = new ArrayList<Map>();


    int colCount = 0;

    if(lines.length > 1){

        String keyLine = lines[0];

        String[] keys = keyLine.split(",");

        for(int i = 1; i < lines.length; i++){

            colCount = 0;
            Map<String, Object> rawObj = new HashMap<String, Object>();

            try {

                String[] values = lines[i].split(",");

                for(String value: values){

                    rawObj.put(keys[colCount], value);
                    colCount++;
                }   

            } catch (Exception e) {

            }

            dataList.add(rawObj);
        }
    }


    Map<String, Object> rawObj = new HashMap<String, Object>();
    rawObj.put("data", dataList);
    Gson gson = new Gson();

    String res = gson.toJson(rawObj);

    return res;
}

String data = "email_from,email_to,DATE_CHANGED\r\nsamwilliams@gmail.com, mike_haley@gmail.com, 1447666867\r\nsmithpaul@gmail.com, angierussell@gmail.com, 1447668867";

但我不确定它是否是一个有效的代码。