1

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);
    }
}
OhadR
  • 6,637
  • 3
  • 39
  • 48
veena
  • 749
  • 1
  • 6
  • 21
  • Aaaaand what happens when you run the code? –  Feb 11 '15 at 16:26
  • It is giving me arrayoutof bound exception.when i just executed File.java it displayed me that column. but not able to store that column in GsonExample. its giving errors – veena Feb 11 '15 at 16:30
  • **Where** is it giving the exception? –  Feb 11 '15 at 16:31
  • at line value2= datavalue[1]; also some runtime error While i created File object – veena Feb 11 '15 at 16:34
  • Okay, so you're trying to assign the item of `datavalue` at index 1 to something, and it's throwing an exception telling you that an array is out of bounds. What does that tell you about `datavalue`? –  Feb 11 '15 at 16:35
  • ...I think it helps if you actually serialize the data you want to serialize. – EpicPandaForce Feb 11 '15 at 16:37
  • @EpicPandaForce when i use System.out.println(value2) its displaying the values of 2nd column from file – veena Feb 11 '15 at 16:40
  • That is wonderful, but you are not giving a `List` or `String[]` to the `String json = gson.toJson(obj);` method in `obj` parameter. – EpicPandaForce Feb 11 '15 at 16:41
  • ok how can i do that. should i declare variable of type list and assign obj to it – veena Feb 11 '15 at 16:46

3 Answers3

3

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

Community
  • 1
  • 1
anquegi
  • 9,627
  • 3
  • 41
  • 60
  • Gson does good conversions to JSON. Are you saying the problem is with Gson versus the code? – Jose Martinez Feb 11 '15 at 16:34
  • this is fine but i want to read from file i have 4 columns Id,Query,time,Url. And i want to extract query column put it in json format. Also i dont have much understanding of code. – veena Feb 11 '15 at 16:36
  • If your file is in that format, I think that you should use opencsv for reading that file, will be better if you have the data in column format in that file – anquegi Feb 11 '15 at 16:42
  • @JoseMartinez yes it should write to a file called file.json. but it was just opening blank {} file. – veena Feb 11 '15 at 16:43
  • No I said that I prefer that library for parsing and reading JSON from java, is the one that use play Framework, and I like also it – anquegi Feb 11 '15 at 16:48
  • @anquegi I am working on project of Query autocompletion. and i want to send response as json using servlets. so i want this text file to be in json format. will this csv do that. I dont no whether it is right or wrong – veena Feb 12 '15 at 15:07
  • @Veena I think that using OpenCsv is the easy way to get a file that have the format similar to csv and return the objects for each row, with fields each column. Then for serving a json, I think that your servlet doesn't need a file it must return Content-Type → application/json; charset=utf-8 – anquegi Feb 12 '15 at 17:50
  • I added to the answer how to return a json from servlet is in another answer here in stackoverflow. I recommend you to use the answer from Symmetric and User241924, I'm not quite good using servlets – anquegi Feb 12 '15 at 17:55
0

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]);
}
Jose Martinez
  • 9,918
  • 6
  • 41
  • 60
0

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.

hasha
  • 195
  • 1
  • 10