Strange “nameValuePairs” key appear when using Gson

前端 未结 5 1352
我寻月下人不归
我寻月下人不归 2021-02-12 10:17

I am trying to rebuild an Object from its fields( i get the fields as a JSONObject), something like this:

JSONObject jObj = new JSONObject();  

JSO         


        
5条回答
  •  囚心锁ツ
    2021-02-12 11:16

    GSON is a tool for POJO serialization. If you are building JSONObject by yourself there is no need for gSon.toJSon(jObj); you can just call jObj.toString() to get the result.

    The proper GSON usage would be to create POJO object for your data structure.

    Your root object would look like this:

    public class jObj {
        JObj11 jObj11;
        JObj12 jObj12;
    }
    

    After the whole structure is defined this way you can use gSon.toJSon(jObj); serialize it to JSON without any usage of JSONObject. GSON will traverse it and produce the JSON string.

    In your example, GSON tries to serialize the internal structure of the JSONObject Java object, not the JSON structure it represents. As you can see, JSONObject uses nameValuePair to store it's content.

提交回复
热议问题