我有一位服务使用者希望我的服务生成以行分隔的JSONL。如何修改Jackson解析器或提供自定义序列化程序,以便将重新调整的对象数组序列化为JSONL而不是JSON。
例如以下代码
import java.util.Arrays;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class JsonlServiceApplication {
public static void main(String[] args) {
SpringApplication.run(JsonlServiceApplication.class, args);
}
@GetMapping("jsonl")
private ResponseEntity<?> getJsonl(){
Pair<String, String> p1 = Pair.of("foo", "baa");
Pair<String, Integer> p2 = Pair.of("key", 10);
return new ResponseEntity(Arrays.asList(p1, p2), HttpStatus.OK);
}
}
将产生这个JSON:
[
{
"foo": "baa"
},
{
"key": 10
}
]
但消费者希望:
{"foo": "baa"}
{"key": 10}
答案 0 :(得分:0)
也许你可以将你的json解析为Object []并迭代每个元素?那样:
public static void main(String[] args) {
String json = "[{\"foo\":\"baa\"},{\"key\":10}]";
Gson gson = new Gson();
Object yourObj[] = gson.fromJson(json, Object[].class);
Arrays.stream(yourObj).forEach(e -> {
System.out.println(e);
});
}