首页 \ 问答 \ 使JsonNode可序列化(Make JsonNode Serializable)

使JsonNode可序列化(Make JsonNode Serializable)

这似乎很简单,但我没有得到序列化的JsonNode反序列化。 这是我的测试课

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Foo implements Serializable {
    private String string;
    private transient JsonNode jsonNode;

    public Foo(String string, JsonNode jsonNode) {
        this.string = string;
        this.jsonNode = jsonNode;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.defaultWriteObject();
        if (this.jsonNode != null) out.writeObject((new ObjectMapper()).writeValueAsBytes(this.jsonNode));
//        out.writeObject(this.jsonNode.textValue());
    }

    private void readObject(ObjectInputStream in) throws IOException,ClassNotFoundException {
        in.defaultReadObject();
        this.jsonNode = (new ObjectMapper()).readValue(in, JsonNode.class);
    }
}

当我试图反序列化时,我得到了这个错误

com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input

这是单元测试

import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.testng.annotations.Test;

import java.io.*;

import static org.testng.Assert.assertEquals;

public class FooTest {
    @Test
    public void testSerialization() {
        JsonNodeFactory nodeFactory = new JsonNodeFactory(false);
        ObjectNode node = nodeFactory.objectNode();
        ObjectNode child = nodeFactory.objectNode(); // the child
        child.put("message", "test");
        node.put("notification", child);

        Foo foo = new Foo("Bar", node);

        String fileName = "foo.ser";
        try (
                OutputStream file = new FileOutputStream(fileName);
                OutputStream buffer = new BufferedOutputStream(file);
                ObjectOutput output = new ObjectOutputStream(buffer);
        ){
            output.writeObject(foo);
        }
        catch(IOException ex){
            ex.getStackTrace();
        }

        Foo fooNew = null;

        //deserialize the ser file
        try(
                InputStream file = new FileInputStream(fileName);
                InputStream buffer = new BufferedInputStream(file);
                ObjectInput input = new ObjectInputStream (buffer);
        ){
            //deserialize the Object
            fooNew = (Foo) input.readObject();
        }
        catch(ClassNotFoundException ex){
            ex.printStackTrace();
        }
        catch(IOException ex){
            ex.printStackTrace();
        }

        assertEquals(foo, fooNew);
    }
}

This seems to be simple but I failed to get a serialized JsonNode deserialized. Here is my test class

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Foo implements Serializable {
    private String string;
    private transient JsonNode jsonNode;

    public Foo(String string, JsonNode jsonNode) {
        this.string = string;
        this.jsonNode = jsonNode;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.defaultWriteObject();
        if (this.jsonNode != null) out.writeObject((new ObjectMapper()).writeValueAsBytes(this.jsonNode));
//        out.writeObject(this.jsonNode.textValue());
    }

    private void readObject(ObjectInputStream in) throws IOException,ClassNotFoundException {
        in.defaultReadObject();
        this.jsonNode = (new ObjectMapper()).readValue(in, JsonNode.class);
    }
}

When I tried to deserialize I got this error

com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input

Here is the unit test

import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.testng.annotations.Test;

import java.io.*;

import static org.testng.Assert.assertEquals;

public class FooTest {
    @Test
    public void testSerialization() {
        JsonNodeFactory nodeFactory = new JsonNodeFactory(false);
        ObjectNode node = nodeFactory.objectNode();
        ObjectNode child = nodeFactory.objectNode(); // the child
        child.put("message", "test");
        node.put("notification", child);

        Foo foo = new Foo("Bar", node);

        String fileName = "foo.ser";
        try (
                OutputStream file = new FileOutputStream(fileName);
                OutputStream buffer = new BufferedOutputStream(file);
                ObjectOutput output = new ObjectOutputStream(buffer);
        ){
            output.writeObject(foo);
        }
        catch(IOException ex){
            ex.getStackTrace();
        }

        Foo fooNew = null;

        //deserialize the ser file
        try(
                InputStream file = new FileInputStream(fileName);
                InputStream buffer = new BufferedInputStream(file);
                ObjectInput input = new ObjectInputStream (buffer);
        ){
            //deserialize the Object
            fooNew = (Foo) input.readObject();
        }
        catch(ClassNotFoundException ex){
            ex.printStackTrace();
        }
        catch(IOException ex){
            ex.printStackTrace();
        }

        assertEquals(foo, fooNew);
    }
}

原文:https://stackoverflow.com/questions/31861354
更新时间:2022-12-22 21:12

最满意答案

我看了一下https://github.com/tminglei/slick-pg/blob/master/addons/spray-json/src/test/scala/com/github/tminglei/slickpg/PgSprayJsonSupportSuite.scala

所以我把它合并为:

allEvents.filter(row => row.product.+>("category_id") ?| ids.map{_.id}.toList.bind)

I had a look into https://github.com/tminglei/slick-pg/blob/master/addons/spray-json/src/test/scala/com/github/tminglei/slickpg/PgSprayJsonSupportSuite.scala

So I combined this into:

allEvents.filter(row => row.product.+>("category_id") ?| ids.map{_.id}.toList.bind)

相关问答

更多
  • 你必须过滤哪些项目进入max() 。 你可以在那里使用生成器表达式: max_stock = max((kv for kv in stock.iteritems() if kv[1] != 'NaN'), key=operator.itemgetter(1)) 请注意,如果过滤后没有剩余项目,这可能会引发ValueError ! 你可以使用try...except语句来处理这种情况: try: max_stock = max((kv for kv in stock. ...
  • 你不能使用| 在Jinja2表达式中运行除Jinja2过滤器操作之外的任何其他操作。 使用{%%}或{{}} (等等)的每个语句都不是python。 这是一个Jinja语言,lexed,由Jinja解析并执行。 您放置的每一段代码都不会像您那样被“摧毁”,但即使是+也会在Jinja2的解析器模块中解析并执行( github-Jinja2 / parser.py#L450 )。 因此| 是Jinja语法的象征,不能颠倒它的python意义。 您可以调用方法的原因是因为您的对象仍然是真实的,并且它们保留了所有的 ...
  • 我看了一下https://github.com/tminglei/slick-pg/blob/master/addons/spray-json/src/test/scala/com/github/tminglei/slickpg/PgSprayJsonSupportSuite.scala 所以我把它合并为: allEvents.filter(row => row.product.+>("category_id") ?| ids.map{_.id}.toList.bind) I had a look int ...
  • 看起来您的用例非常适合SOLR中的Dismax / Edismax查询解析器: https ://cwiki.apache.org/confluence/display/solr/The+DisMax+Query+Parser 尤其是: qf Query Fields: specifies the fields in the index on which to perform the query. 注释:fq的问题在于它们没有经过与q参数相同的查询预处理。 但是,fqs确实支持布尔逻辑。 Looks ...
  • 不要使用Swift的字符串插值,而应该通过%@使用NSPredicate的参数替换支持: .filter("code IN %@", myCodeArray) Swift的字符串插值语法( "\(someVariable)" )将变量的字符串表示形式插入到字符串中。 整数数组的字符串表示形式为[123459, 1031020] , 在NSPredicate格式字符串中无效 。 使用%@将对象替换为谓词,而无需担心对象的Swift字符串表示是否与NSPredicate期望的匹配。 Instead of us ...
  • 运营商%和&具有不同的优先级。 所以_ & 1 == 0尝试将1与0进行比较,然后对布尔结果执行& 。 请参阅Scala参考 - 6.12.3中缀操作 : 增加优先顺序: (all letters) | ^ & = ! < > : + - * / % (all other special characters) Operators % and & have different priorities. So _ & 1 == 0 tries to compare one to zero and then p ...
  • Cyrille的链接似乎有点不同,但这种方法可能会扩展到涵盖你的情况。 如果这只是一个地方,那么好的旧if什么问题: val date2 = TableQuery[DatesDB] val query = if (condition) date2.filter(d => (d.sk < sk)) else date2.filter(d => (d.sk <= sk)) val action = query.result 另一个想法 val date2 = TableQuery[DatesDB] val ...
  • 以下方法将为给定用户返回给定线程+的upvote +的帖子数组: getMyUpVotes(threadId: string, uid: string): Observable { return this.af.database.list(`threadsMeta/${threadId}/posts`).take(1) // Flatten the posts array to emit each post individually. .mergeMap(val => val) ...
  • 您的observable是一个数组项目。 它不是该数组中项目的可观察数据。 过滤函数中的x=> x.type ==="member" : x=> x.type ==="member"是一个数组,因此x.type不存在。 为了实现你想要的,你需要遍历那个数组: getMembers (): Observable { var one = this.http.get(this.memberUrl) .map( this.extractData ) ...
  • 在你的表达内:输入 "APACC", "APBATT, "APCHG", "APLB" Inside your expression: type in "APACC", "APBATT, "APCHG", "APLB"

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。