繁体   English   中英

无法从CBOR文件读取数据

[英]Unable to read data from CBOR File

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

我正在使用Jackson CBOR API读写文件中的数据,并将数据写入文件。

我正在使用ObjectMapper类的writeValue方法编写TargetModel的实例,但是当我尝试读取数据时,当我尝试使用ReadValue读取对象时,它将引发JsonMappingException

请帮我! 因此,我遇到了严重的麻烦。

主类

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;

}

}

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

ObjectMapper映射器= new ObjectMapper(new CBORFactory()); mapper.writeValue(file,objectToWrite); TargetModel结果= mapper.readValue(文件,TargetModel.class);

分别构造解析器或生成器通常没有多大意义。 另外,请确保使用最新的可用版本。 2.5.3此时。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM