无法从CBOR文件中读取数据

时间:2015-03-04 20:11:01

标签: java json data-binding jackson

我的目标是使用文件将TargetModel类的实例存储为CBOR格式。如果有任何其他方法,它对我有用!

我正在使用Jackson CBOR API来写入和读取数据并将数据写入文件。

我正在使用ObjectMapper Class的writeValue方法来编写TargetModel的实例但是当我尝试读取数据时,当我尝试使用它来读取对象时,它会抛出JsonMappingException ReadValue

请帮帮我!我因此而陷入严重困境。

Mainclass.java

package cborStoring;

public class MainClass {

public static void main (String[] args) throws Exception{

    String targetfilePath = "/home/vaio/Documents/mySampleFile";

    CBORWriter myCborWriter = new CBORWriter();

    TargetModel sampleModel = new TargetModel("rajat", "dfdsf");
//  TestClass sampleModel = new TestClass();

    Object inputObject = (Object)sampleModel;


    myCborWriter.writeObject(inputObject, targetfilePath);

    CBORReader myCborReader = new CBORReader();
    Object readObj = myCborReader.readObject(targetfilePath);

    TargetModel myModel = (TargetModel)readObj;
//  TestClass myModel = (TestClass)readObj;

    System.out.println("Program Ends!");

}
}

CBORWriter.java

package cborStoring;

public class CBORWriter {

public CBORWriter(){

}

public void writeObject(Object inputObject, String targetfilePath) throws Exception{

    FileOutputStream fos = new FileOutputStream(targetfilePath, true);

    if (!(new File(targetfilePath)).exists())
        (new File(targetfilePath)).createNewFile();

    CBORFactory f = new CBORFactory();
    ObjectMapper mapper = new ObjectMapper(f);

    mapper.writeValue(fos,inputObject);


    fos.close();
}

}

CBORReader.java

package cborStoring;

public class CBORReader {

public CBORReader(){

}

public Object readObject(String targetFilePath) throws Exception{

    FileInputStream fis = new FileInputStream(targetFilePath);

    CBORFactory f = new CBORFactory();

    ObjectMapper myMapper = new ObjectMapper(f);

    CBORParser myCborParser = f.createParser(fis);

    //Object readObject = myMapper.readValue(myCborParser, Object.class);
    //Object readObject = myMapper.readValue(myCborParser, TargetModel.class); : This does NOT Work throws JSONMappingException

    Object readObject = myMapper.readValue(myCborParser, TargetModel.class);

    return readObject;

}

}

1 个答案:

答案 0 :(得分:0)

我不知道底层问题是什么,但代码可以简化很多,如下所示:

ObjectMapper mapper = new ObjectMapper(new CBORFactory());    mapper.writeValue(file,objectToWrite);    TargetModel result = mapper.readValue(file,TargetModel.class);

并且分别构建解析器或生成器通常没什么意义。 另外,请务必使用最新版本; 2.5.3此时。