首页 \ 问答 \ 对Jackson的YAML序列化使用标量值的文字样式(Use literal style on scalar values for YAML serialization with Jackson)

对Jackson的YAML序列化使用标量值的文字样式(Use literal style on scalar values for YAML serialization with Jackson)

我正在使用Jackson将对象序列化为YAML( jackson-dataformat-yaml库)。

我想为标量值生成文字样式输出(例如,以下示例中的'description')

---
id: 4711
description: |
  FooBar
  HelloWorld

但我只设法生成这样的引用标量:

---
id: 4711
description: "FooBar\nHelloWorld"

我用来生成ObjectMapper的代码(现在)非常简单:

    YAMLFactory f = new YAMLFactory();
    f.enable(YAMLGenerator.Feature.SPLIT_LINES); // setting does not matter
    ObjectMapper objectMapperYaml = new ObjectMapper(f);
    String yaml = objectMapperYaml.writeValueAsString(someObject);

我想有可能生成文字样式标量值,但我不知道如何。 任何提示都是受欢迎的!


I am using Jackson to serialize objects to YAML (jackson-dataformat-yaml library).

I would like to produce literal style output for scalar values (e.g. 'description' in the following example) like

---
id: 4711
description: |
  FooBar
  HelloWorld

but I only manage to produce quoted scalars like this:

---
id: 4711
description: "FooBar\nHelloWorld"

The code I use to generate the ObjectMapper is (by now) very simple:

    YAMLFactory f = new YAMLFactory();
    f.enable(YAMLGenerator.Feature.SPLIT_LINES); // setting does not matter
    ObjectMapper objectMapperYaml = new ObjectMapper(f);
    String yaml = objectMapperYaml.writeValueAsString(someObject);

I guess there is some possibility to generate literal style scalar values but I don't know how. Any hints are welcome!


原文:https://stackoverflow.com/questions/46526906
更新时间:2023-05-22 08:05

最满意答案

是的,一切都是对象。 但是,一切都是对象并不意味着一切都需要任意属性。

Python中的整数是对象,并且具有属性和方法(它们只是可调用的属性):

>>> x = 6
>>> x.real
6
>>> x.imag
0
>>> x.bit_length()
3

要支持任意属性,对象需要具有__dict__映射。 整数没有这样的映射:

>>> x.__dict__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__dict__'

其他对象与函数一样,例如:

>>> def foo(): pass
...
>>> foo.__dict__
{}
>>> foo.bar = 'baz'

__dict__映射需要付出代价:这些对象的内存占用量更大。 由于Python使用了很多整数,因此为了节省内存而不给它们__dict__映射是有意义的。 无论如何,你很少需要给它们额外的属性。

您可以通过为类提供__slots__类变量来定义自己的类,这些类生成没有__dict__属性的实例; 这定义了实例支持的固定属性。 这可以让您从相同的内存节省中受益:

>>> class Demo(object):
...     __slots__ = ('foo',)
...
>>> d = Demo()
>>> d.foo = 'bar'
>>> d.bar = 'foo'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Demo' object has no attribute 'bar'

反之亦然,如果你创建一个int的子类而不给你的子类一个__slots__变量,你可以向该子类添加任意属性:

>>> class MyInt(int):
...     pass
...
>>> mi = MyInt(6)
>>> mi.foo = 'bar'

Yes, everything is an object. However, everything being an object does not mean that everything takes arbitrary attributes.

Integers in Python are objects, and have attributes and methods (which are just callable attributes):

>>> x = 6
>>> x.real
6
>>> x.imag
0
>>> x.bit_length()
3

To support arbitrary attributes, an object needs to have a __dict__ mapping. Integers don't have such a mapping:

>>> x.__dict__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__dict__'

Other objects do, like functions, for example:

>>> def foo(): pass
...
>>> foo.__dict__
{}
>>> foo.bar = 'baz'

But a __dict__ mapping comes with a price: a larger memory footprint for such objects. Since Python uses a lot of integers, it makes sense to not give them a __dict__ mapping, to save memory. You very rarely would need to give them extra attributes anyway.

You can define your own classes that produce instances without a __dict__ attribute, by giving your class a __slots__ class variable; this defines the fixed attributes an instance supports. This lets you benefit from the same memory savings:

>>> class Demo(object):
...     __slots__ = ('foo',)
...
>>> d = Demo()
>>> d.foo = 'bar'
>>> d.bar = 'foo'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Demo' object has no attribute 'bar'

And vice-versa, if you create a subclass of int and not give your subclass a __slots__ variable, you can add arbitrary attributes to that subclass:

>>> class MyInt(int):
...     pass
...
>>> mi = MyInt(6)
>>> mi.foo = 'bar'

相关问答

更多
  • 这里的问题在于这是真的两个问题 - 一个问题是关于继承问题,在这种情况下答案是“几乎一切”,另一个是关于引用类型vs值类型/内存/拳击,这种情况的答案是“否”。 遗产: 在C#中,如下: 所有值类型(包括枚举和可空类型)都派生自System.Object 。 所有类,数组和委托类型都派生自System.Object 。 接口类型不是从System.Object派生的。 它们都可以转换为System.Object ,但接口只能从其他接口类型派生,而System.Object不是接口类型。 没有指针类型从Sys ...
  • 添加using指令的目的只是允许您在该命名空间中使用名称而不对它们进行完全限定。 所以你不必添加using指令。 你可以写: public static MvcHtmlString ObjectTable(this HtmlHelper helper, ICollection objects, ICollection header) 或者,由于object 始终是System.Object的别名,您可以编写: public static MvcHtm ...
  • 请注意, object实例没有__dict__属性: >>> dir(object()) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__'] 在派生类中说明此行为的示例: >>> class Foo(object): ... ...
  • 假设你有一个类 >>> class Cls(object): ... foo = 1 ... bar = 'hello' ... def func(self): ... return 'call me' ... >>> obj = Cls() 在对象上调用dir让您回溯该对象的所有属性,包括python特殊属性。 虽然一些对象属性是可调用的,如方法。 >>> dir(obj) ['__class__', '__delattr__', '__dict__', '__d ...
  • 你可以使用我的古老的Bunch配方,但如果你不想做一个“束类”,Python中就已经存在一个非常简单的类 - 所有函数都可以有任意的属性(包括lambda函数)。 所以,以下作品: obj = someobject obj.a = lambda: None setattr(obj.a, 'somefield', 'somevalue') 无论是明显的丢失与可敬的Bunch食谱相比都是可以的,是一种风格决定,我当然会放弃给你。 You could use my ancient Bunch recipe, b ...
  • 是的,一切都是对象。 但是,一切都是对象并不意味着一切都需要任意属性。 Python中的整数是对象,并且具有属性和方法(它们只是可调用的属性): >>> x = 6 >>> x.real 6 >>> x.imag 0 >>> x.bit_length() 3 要支持任意属性,对象需要具有__dict__映射。 整数没有这样的映射: >>> x.__dict__ Traceback (most recent call last): File "", line 1, in ...
  • 解决这个问题的一种常见的鸭式Python解决方案是(尝试)将你得到的东西转换成你需要的东西。 例如,如果您需要一个整数: def getconstants(arg): try: arg = int(arg) except: raise TypeError("expected integer, or something that can be converted to one, but got " + repr(arg)) int类型的构造函数知道如何处理许多 ...
  • 一个反例是在Java Integer是一个对象,但int不是,这意味着不同的操作同时适用于两者(当然,在最近的Java中,自动转换到对象版本/从对象版本转换,但这会引入意外的性能问题)。 由于间接性,对象稍慢一些,但更灵活; 一切都是一个对象意味着一切都表现一贯。 Java也是一个例子:一个数组不是一个对象, ArrayIterator是事后(甚至是多个第三方实现) ArrayIterator的东西,因此与集合类迭代器的工作方式不一致。 A counterexample would be that in J ...
  • 如果您使用的是Python 3.3+,请使用types.SimpleNamespace : >>> import types >>> a = types.SimpleNamespace() >>> a.attr1 = 123 >>> a.attr2 = '123' >>> a.attr3 = [1,2,3] >>> a.attr1 123 >>> a.attr2 '123' >>> a.attr3 [1, 2, 3] If you are using Python 3.3+, use types.Simp ...
  • JavaScript中的字符串不是String的实例。 如果你做new String('my string')那么它会。 否则它是一个原始的,当你调用它的方法时,它将被动态地转换为一个String对象。 如果你想获得字符串的值,你需要调用toString() ,如下所示: var s = new String("hello world!"); s.x = 5; console.log(s.x); //5 console.log(s); //[object Object] console.log(s.toSt ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)