Retrofit + Gson无法解析简单的Map

huangapple go评论85阅读模式
英文:

Retrofit + Gson can not parse simple Map

问题

I have a JSON as follows

{
  "1.2.3.4": "domain1.com",
  "1.2.3.5": "domain2.com"
}

And a model

public class DnsLookup {
  @Getter @Setter private Map<String, String> entry;
}

And retrofit query interface

@GET("/dns/")
Call<DnsLookup> getDns(@QueryMap Map<String, String> params);

When I make the query, I get null in dns.

Call<DnsLookup> call = service.getDns(queryMap);
Response<DnsLookup> response;
response = call.execute();
var dns = response.body();

Actually the original JSON is

{
  "1.2.3.4": [
    "domain1.com", "domain1-1.com"
  ],
  "1.2.3.5": [
    "domain2.com"
  ]
}

And I have tried the following model to only get null. Since the following didn't work, I broke the problem to just key-value pairs. To my surprise, the simple map also didn't work.

public class DnsLookup {
  @Getter @Setter private Map<String, List<String>> entry;
}

Am I doing a noob mistake?

英文:

I have a JSON as follows

{
  &quot;1.2.3.4&quot;: &quot;domain1.com&quot;,
  &quot;1.2.3.5&quot;: &quot;domain2.com&quot;
}

And a model

public class DnsLookup {
  @Getter @Setter private Map&lt;String, String&gt; entry;
}

And retrofit query interface

  @GET(&quot;/dns/&quot;)
  Call&lt;DnsLookup&gt; getDns(@QueryMap Map&lt;String, String&gt; params);

When I make the query, I get null in dns.

    Call&lt;DnsLookup&gt; call = service.getDns(queryMap);
    Response&lt;DnsLookup&gt; response;
    response = call.execute();
    var dns = response.body();

Actually the original JSON is

{
  &quot;1.2.3.4&quot;: [
    &quot;domain1.com&quot;, &quot;domain1-1.com&quot;
  ],
  &quot;1.2.3.5&quot;: [
    &quot;domain2.com&quot;
  ]
}

And I have tried the following model to only get null. Since the following didn't work, I broke the problem to just key-value pairs. To my surprise, the simple map also didn't work.

public class DnsLookup {
  @Getter @Setter private Map&lt;String, List&lt;String&gt;&gt; entry;
}

Am I doing a noob mistake?

答案1

得分: 1

Sure, here's the translated code:

使用

@GET("/dns/")
Call<Map<String, List<String>>> getDns(@QueryMap Map<String, String> params);

替代:

@GET("/dns/")
Call<DnsLookup> getDns(@QueryMap Map<String, String> params);
英文:

Use:

@GET(&quot;/dns/&quot;)
Call&lt;Map&lt;String, List&lt;String&gt;&gt;&gt; getDns(@QueryMap Map&lt;String, String&gt; params);

Instead of:

@GET(&quot;/dns/&quot;)
Call&lt;DnsLookup&gt; getDns(@QueryMap Map&lt;String, String&gt; params);

huangapple
  • 本文由 发表于 2020年9月2日 16:58:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63702121.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定