简体   繁体   English

如何从对象列表和JSON模式创建JSON字符串?

[英]How to create a JSON String from a list of objects and a JSON schema?

I have a list of objects which needs to be converted to JSON. 我有一个对象列表,需要将其转换为JSON。 I also have a JSON schema corresponding to which the objects should be placed in the JSON to be created. 我还有一个JSON模式,应将对象放置在要创建的JSON中。 How can I achieve this? 我该如何实现? I cannot seem to find any references on the internet. 我似乎在互联网上找不到任何参考。 Is this possible? 这可能吗? Any help would be much appreciated. 任何帮助将非常感激。

There is no Java technology that that uses a json schema to influence serialization that I am aware of. 据我所知,没有Java技术使用json模式来影响序列化。 If you use a library such as Jackson to serialize, it's up to you to use the available customization mechanisms to make any changes to the defaults needed to conform to the schema. 如果您使用Jackson之类的库进行序列化,则取决于您使用可用的自定义机制对符合架构所需的默认值进行任何更改。

If it's JavaScript, you can do it using Ajv and custom keywords that would generate the object you need as a side-effect of validation process. 如果使用的是JavaScript,则可以使用Ajv和自定义关键字来完成,这些关键字将生成所需的对象,作为验证过程的副作用。 Most likely you would have to define template that will be validated and the data that needs to be embedded in this template will be passed as a context into validation function: 您最有可能必须定义将要验证的模板,并且需要嵌入此模板中的数据将作为上下文传递到验证函数中:

var validate = ajv.compile(schema);
var context = { data: { /* ... */ } };
validate.call(context, template);
console.log(template); // template with inserted data

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

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