简体   繁体   English

将字符串转换为gson对象

[英]converting string to gson object

I have a string output from server and I am trying to extract some values form the string. 我有一个从服务器输出的字符串,我试图从字符串中提取一些值。

Here is the output from server: 这是服务器的输出:

jsonString =

{
  "MEANING":"reduce",
  "DISPLAY":"",
  "TYPE_CD":1,
  "SELECTED_IND":1,
  "CNT":1,
  "SOURCES":[
              { "a":1 }
            ]
}

Code: 码:

JsonReader reader = new JsonReader(new StringReader(jsonString));
DataObject obj1 = new Gson().fromJson(reader, DataObject.class);

DataObject Class: DataObject类别:

DataObject
{ 
    private int MEANING;
    private int CNT;
    private String TYPE_CD;
    private String DISPLAY;
    private String MEANING;
    private List<Long> SOURCES;

    public String getSourceTypeMeaning()
     {
       return this.MEANING;
     }

    public String getSourceTypeDisplay() 
     {
       return this.DISPLAY;
     }

    public String getSourceTypeCd() 
     {
       return this.TYPE_CD;
     }

    public int getSourceCount() 
     {
       return this.CNT;
     }

    public List<Long> getSourceList() 
     {
       return this.SOURCES;
     }
}

but getting this error 但是得到这个错误

Expected a string but was BEGIN_OBJECT at line 1 column 132

I am not able to find the issue with my code. 我的代码找不到问题。

Other answers are pointing out that the problem is in the SOURCES field, and that's true, but the solutions they're giving are not correct... 其他答案指出问题出在SOURCES字段中,这是事实,但是他们提供的解决方案不正确...

You can't use just a Map to parse the SOURCES field, because this field is indeed an array ! 您不能仅使用Map来解析SOURCES字段,因为该字段的确是数组 You have: 你有:

"SOURCES": [ ... ]

Since you have square brackets [ ] , you have an array! 因为有方括号[ ] ,所以有数组! And it's true there's a Map , but it is contained in the array... 确实有一个Map ,但是它包含在数组中...

So, what you need to parse that field correctly is: 因此,您需要正确解析该字段是:

private List<Map<String, int>> SOURCES;

Note that we use a Map to allow the content of SOURCES to have multiple and unknown values, so that this code could parse not only your JSON, but also something like: 请注意,我们使用Map来允许SOURCES的内容具有多个未知值,以便此代码不仅可以解析您的JSON, 可以解析以下内容:

"SOURCES":[
              { "a":1, "b":2 },
              { "c":3 },
              { "x":99, "y":98, "z":97 }
          ]

SOURCES variable should be Map<String,Long> ,because in JSON string SOURCES is key-value collection ("a":1) where "a" is string and 1 is number. SOURCES变量应该为Map<String,Long> ,因为在JSON字符串中SOURCES是键值集合("a":1) ,其中“ a”是字符串,1是数字。

Hope this helps. 希望这可以帮助。

Check this 检查一下

"SOURCES":[
              { "a":1 }
 ]

This will represent a List of map not List of long. 这将代表地图列表而不是长列表。

So change your List<long> to List<Map<String, Long>> or List<Map<Object, Long>> . 因此将List<long>更改为List<Map<String, Long>>List<Map<Object, Long>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM