Ismail
Ismail

Reputation: 95

Get JSON without key using gson java

import java.util.List;
import com.google.gson.annotations.Expose;
public class TabCompRec {
    @Expose private List<TabDataCell> cells;

    public List<TabDataCell> getCells() {
        return cells;
    }

    public void setCells(List<TabDataCell> cells) {
        this.cells = cells;
    }
}

import com.google.gson.annotations.Expose;
public class TabDataCell {
    @Expose private String cellValue;

    public String getCellValue() {
        return cellValue;
    }

    public void setCellValue(String cellValue) {
        this.cellValue = cellValue;
    }
}

import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class TabMain {
    public static void main(String[] args) {
        TabDataCell tdc1 = new TabDataCell("123");
        TabDataCell tdc2 = new TabDataCell("456");

        TabCompRec tcr = new TabCompRec();
        tcr.setCells(Arrays.asList(tdc1, tdc2));

        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        System.out.println(gson.toJson(tcr));
    }
}

Output am getting for the above code:

{ "cells": [ { "cellValue": "123" }, { "cellValue": "456" } ] }

But i want json like below, without changing the domain object structure. I got a workaround code, which iterate the above json and convert as below. But I would like to know any gson utilities available to get the output like this:

{ "cells": [ "123", "456" ] }

Upvotes: 1

Views: 426

Answers (2)

Michał Ziober
Michał Ziober

Reputation: 38690

You can implement custom serialiser implementing com.google.gson.JsonSerializer interface:

class TabDataCellJsonSerializer implements JsonSerializer<TabDataCell> {
    @Override
    public JsonElement serialize(TabDataCell src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src.getCellValue());
    }
}

You can register it like below:

Gson gson = new GsonBuilder()
        .registerTypeAdapter(TabDataCell.class, new TabDataCellJsonSerializer())
        .create();

Upvotes: 1

Jens
Jens

Reputation: 69470

Make cells a list of String instead of list of TabDataCell

import java.util.List;
import com.google.gson.annotations.Expose;
public class TabCompRec {
    @Expose private List<String> cells;

    public List<String> getCells() {
        return cells;
    }

    public void setCells(List<String> cells) {
        this.cells = cells;
    }
}

import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class TabMain {
    public static void main(String[] args) {
        TabCompRec tcr = new TabCompRec();
        tcr.setCells(Arrays.asList("123", "456"));

        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        System.out.println(gson.toJson(tcr));
    }
}

This should give you the correct result

Upvotes: 0

Related Questions