对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
最满意答案
是的,一切都是对象。 但是,一切都是对象并不意味着一切都需要任意属性。
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'
相关问答
更多-
.NET中的一切都是对象吗?(Is everything in .NET an object?)[2021-10-24]
这里的问题在于这是真的两个问题 - 一个问题是关于继承问题,在这种情况下答案是“几乎一切”,另一个是关于引用类型vs值类型/内存/拳击,这种情况的答案是“否”。 遗产: 在C#中,如下: 所有值类型(包括枚举和可空类型)都派生自System.Object 。 所有类,数组和委托类型都派生自System.Object 。 接口类型不是从System.Object派生的。 它们都可以转换为System.Object ,但接口只能从其他接口类型派生,而System.Object不是接口类型。 没有指针类型从Sys ... -
一切都是对象(All thing is Object)[2023-07-30]
添加using指令的目的只是允许您在该命名空间中使用名称而不对它们进行完全限定。 所以你不必添加using指令。 你可以写: public static MvcHtmlString ObjectTable(this HtmlHelper helper, ICollectionobjects, 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 ...
-
如果一切都是对象,为什么我不能为某些对象添加属性?(If everything is an object, why can't I add attributes to some?)[2022-03-13]
是的,一切都是对象。 但是,一切都是对象并不意味着一切都需要任意属性。 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对象,如果它的属性不被使用?(How can I avoid type checking a python object if its attributes aren't used?)[2024-03-06]
解决这个问题的一种常见的鸭式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 - 为什么我无法将新属性添加到“字符串”对象?(JavaScript - Why can't I add new attributes to a “string” object?)[2022-05-17]
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 ...