This is a test version of Biostars. For the public version, visit https://www.biostars.org.
converting SAMRecord to JSON or String format

I want to develop RESTful web service which will provide bam reads in JSON format. I used SamFileReader (htsjdk.samtools.SAMFileReader) for reading bam file and then using SAMRecordIterator to get SAMRecord. But when I try to convert it into String/ JSON it throws following error :

Method not implemented for: class htsjdk.samtools.SAMSequenceRecord (through reference chain: htsjdk.samtools.BAMRecord["header"]->htsjdk.samtools.SAMFileHeader["sequenceDictionary"]->htsjdk.samtools.SAMSequenceDictionary["sequences"]->java.util.UnmodifiableRandomAccessList[0]->htsjdk.samtools.SAMSequenceRecord["id"])

I tried following ways to create JSON for SamRecord :

  1. Used com.fasterxml.jackson.databind.ObjectMapper and ObjectWriter with "writeValueAsString()" API.
  2. Used directly Response Body annotation for request URL method.
  3. Tried to use JSONSerializer from "net.sf.json" and same error occured.

Is there any other way to convert SamRecord to JSON/String ?

sam json samrecord htsjdk

1 answer

SAMRecord is not treated as a POJO: when jackson tries to serialize a samrecord, it finds that a samrecord is linked to a header. and jacksons tries to serialize everything

https://samtools.github.io/htsjdk/javadoc/htsjdk/htsjdk/samtools/SAMRecord.html#getHeader--

which contains a whole sequence dictionary

https://samtools.github.io/htsjdk/javadoc/htsjdk/htsjdk/samtools/SAMFileHeader.html#getSequenceDictionary--

which contains a list of https://samtools.github.io/htsjdk/javadoc/htsjdk/htsjdk/samtools/SAMSequenceRecord.html

which contains a getter "getId" with the following implementation: https://github.com/samtools/htsjdk/blob/master/src/main/java/htsjdk/samtools/AbstractSAMHeaderRecord.java#L87

  public String getId() {
        throw new UnsupportedOperationException("Method not implemented for: " + this.getClass());
    }

the best way is to create your very own serializer.

FYI, I wrote a SAMTojson : https://github.com/lindenb/jvarkit/blob/master/src/main/java/com/github/lindenb/jvarkit/util/samtools/SamJsonWriterFactory.java

....

Log in to answer this question.