开发者

GSON: Missing fields when converting Java objects to JSON with gson.toJson

开发者 https://www.devze.com 2023-03-20 23:24 出处:网络
I\'m using the GSON 1.7.1 library to create a JSON representation of a number of Java objects. This works well, however when the class extends eg Vector< String > then the fields are missing from t

I'm using the GSON 1.7.1 library to create a JSON representation of a number of Java objects. This works well, however when the class extends eg Vector< String > then the fields are missing from the output.

Actual Output:

[
  "String 1",
  "String 2"
]

Required/Expected output: I would like both the contents of the new object's fields to be displayed as well as the contents of the Vector I'm extending. eg something like this...

{
  "extraInfo": "Extra Info",
  "vector": [
     "String 1",
     "String 2"
  ]
}

I'm adding this to existing code so I don't have the option of changing the class structure from extending type Vector< String > to containing a field of type Vector< String >

Here's the example source code...

import java.util.Vector;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class ExtendedStringVector extends Vector<String>{

    private String extraInfo = "";

    public String toString(){
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String jsonOutput = gson.toJson(this);
        return jsonOutput;
    }

    p开发者_运维知识库ublic void setExtraInfo(String test) {
         this.extraInfo = test;
    }

    public String getExtraInfo() {
        return extraInfo;
    }

    public static void main(String[] args) {
        ExtendedStringVector esv = new ExtendedStringVector();
        esv.add("String 1");
        esv.add("String 2");
        esv.setExtraInfo("Extra Info");
        System.out.println(esv.toString());
    }
}

There is some documentantion here which looks like it is close to what I need however it doesn't cover my case.

Is there an easy way to get the output I expect? Have I missed a simple settings or type parameter?


Your required output is an invalid JSON structure.

Something like this is valid:

{
  "extraInfo": "Extra Info",
  "vector" : [
     "String 1",
     "String 2"
  ]
}

To achieve this, you need an object that composes of a String object, and a list (can be vector or array or List) of String objects.

See this question.


I looked through a few Java-to/from-JSON libraries, and didn't see anything that had a built-in feature like what you're after. Custom serialization/deserialization is necessary.

0

精彩评论

暂无评论...
验证码 换一张
取 消