converting java object to json

I am trying to convert java object to json. I have a java class which reads a specific column from a text file. And I want to store that read column in json format.

Here is my code. I dont know where I am going wrong.

Thanks in advance.

File.java

public class File {

    public File(String filename)
            throws IOException {
        filename = readWordsFromFile("c:/cbir-2/sample/aol.txt");
    }

    public String value2;

    public String readWordsFromFile(String filename)
            throws IOException {
        filename = "c:/cbir-2/sample/aol.txt";
        // Creating a buffered reader to read the file
        BufferedReader bReader = new BufferedReader(new FileReader(filename));
        String line;
        //Looping the read block until all lines in the file are read.

        while ((line = bReader.readLine()) != null) {
            // Splitting the content of tabbed separated line
            String datavalue[] = line.split("t");
            value2 = datavalue[1];
            // System.out.println(value2);
        }

        bReader.close();

        return "File [ list=" + value2 + "]";
    }
}

GsonExample.java

import com.google.gson.Gson;

public class GsonExample {
    public static void main(String[] args)
            throws IOException {
        File obj = new File("c:/cbir-2/sample/aol.txt");
        Gson gson = new Gson();
        // convert java object to JSON format,
        // and returned as JSON formatted string
        String json = gson.toJson(obj);

        try {
            //write converted json data to a file named "file.json"
            FileWriter writer = new FileWriter("c:/file.json");
            writer.write(json);
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(json);
    }
}

Looks like you might be overwriting value2 for each line.

value2= datavalue[1];

EDIT: Can you make value2 a List and add to it.

value2.add(datavalue[1]);

EDIT2: You need to check the size of the array before using it.

if (datavalue.length >= 2){
    value2.add(datavalue[1]);
}

I recommend you to use Jackson High-performance JSON processor.

from http://jackson.codehaus.org/

here is the sample from their tutorial

The most common usage is to take piece of JSON, and construct a Plain Old Java Object ("POJO") out of it. So let's start there. With simple 2-property POJO like this:

// Note: can use getters/setters as well; here we just use public fields directly:

public class MyValue {
  public String name;
  public int age;
  // NOTE: if using getters/setters, can keep fields `protected` or `private`
}

we will need a com.fasterxml.jackson.databind.ObjectMapper instance, used for all data-binding, so let's construct one:

ObjectMapper mapper = new ObjectMapper(); // create once, reuse

The default instance is fine for our use -- we will learn later on how to configure mapper instance if necessary. Usage is simple:

MyValue value = mapper.readValue(new File("data.json"), MyValue.class);
// or:
value = mapper.readValue(new URL("http://some.com/api/entry.json"), MyValue.class);
// or:
value = mapper.readValue("{"name":"Bob", "age":13}", MyValue.class);

And if we want to write JSON, we do the reverse:

mapper.writeValue(new File("result.json"), myResultObject);
// or:
byte[] jsonBytes = mapper.writeValueAsBytes(myResultObject);
// or:
String jsonString = mapper.writeValueAsString(myResultObject);

Processing a file that have the information in columns like a csv I recomend for this task use opencsv here is an example for information in 5 columns separated by '|'

import com.opencsv.CSVReader;
import pagos.vo.UserTransfer;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by anquegi on
 */
public class CSVProcessor {

    public List<String[]> csvdata = new ArrayList<String[]>();

    public CSVProcessor(File CSVfile) {

        CSVReader reader = null;

        try {
            reader = new CSVReader(new FileReader(CSVfile),'|');
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Logger.error("Cannot read CSV: FileNotFoundException");
        }
        String[] nextLine;
        if (reader != null) {
            try {
                while ((nextLine = reader.readNext()) != null) {
                    this.csvdata.add(nextLine);
                }
            } catch (IOException e) {
                e.printStackTrace();
                Logger.error("Cannot read CSV: IOException");
            }
        }


    }



    public List<TransfersResult> extractTransfers() {

        List<TransfersResult> transfersResults = new ArrayList<>();


        for(String [] csvline: this.csvdata ){

            if(csvline.length >= 5){
            TransfersResult transfersResult = new TransfersResult(csvline[0]
                    ,csvline[1],csvline[2],csvline[3],csvline[4]);

            // here transfersResult is a pojo java object
            }

        }

        return transfersResults;

    }

}

and for returning a json from a servlet this is solved in this question in stackoverflow

How do you return a JSON object from a Java Servlet


The reason for the exception could be value2=datavlue[1];

means during your first execution of while loop , you are trying to assign seconds element(datavalue[1]) in the String array to value2 , which is not created by then.So its giving that exception.

链接地址: http://www.djcxy.com/p/46080.html

上一篇: 使用ajax从servlet获取值

下一篇: 将java对象转换为json