2

I have a service consumer who wants my service to produce line delimited JSONL. How can I modify the Jackson parser or provide a custom serializer so that a retuned array of objects is serialized as JSONL and not JSON.

For example the following code

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);
    }
}

Will produce this JSON:

[
  {
    "foo": "baa"
  },
  {
    "key": 10
  }
]

But the consumer would like:

{"foo": "baa"}
{"key": 10}
Mark
  • 2,260
  • 18
  • 27
  • 2
    You shouldn't try to do that, if you consumer can't handle an standard Json, the correction should be consumer side, not producer side. – Zorglube Nov 17 '17 at 16:10
  • I tend to agree, they don't ;-) – Mark Nov 17 '17 at 21:31
  • 1
    So you're f***ed ;-) Try your best to change the mind of your Json consumer team. – Zorglube Nov 20 '17 at 09:37
  • I'm thinking of negotiating to return a RxJava `Observable` or Spring `Flux` object using Spring Reactive one object at a time. Possibly a happy compromise. – Mark Nov 21 '17 at 16:32
  • 1
    I don’t agree, if you have a requirement on jsonl you should try to deliver what was asked for. Not try to deliver whatever you think works best. – sayil aguirre May 03 '21 at 18:19

1 Answers1

0

Maybe you can parse your json into an Object[] and iterate on each elem ? like that :

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);
        });
    }
Zibaire
  • 119
  • 5
  • The consumer could do that but that doesn't help with making the service produce jsonl – Mark Nov 17 '17 at 16:07