java-使用GSON解析没有特定结构的JSON字段

java-使用GSON解析没有特定结构的JSON字段,第1张

概述我正在使用EmpireAvenueAPI开发一个Android应用程序.该API使用JSON,而我正在使用GSON库来解析该API中的数据.这是问题所在:我有一个像这样的JSON结构:{type:"earnings",info:{earnings:64.09dividends:1277.34gains:1997.05 @H_502_0@我正在使用EmpireAvenue API开发一个Android应用程序.
该API使用JsON,而我正在使用GSON库来解析该API中的数据.
这是问题所在:

@H_502_0@我有一个像这样的JsON结构:

@H_502_0@

{    type: "earnings",    info: {        earnings: 64.09        divIDends: 1277.34        gains: 1997.05        expenses: 4895.51        shares_bought: 210        shares_bought_user_count: 2        shares_sold: 0        shares_sold_user_count: 0    },    created: "2011-04-16 11:32:37"},{    type: "following",    info: [            {                ticker: "SolPHE"                full_name: "Rodrigo Bermudez Salazar"                @R_403_6818@_name: "My Recommended Buys"            },            {                ticker: "SolPHE"                full_name: "Rodrigo Bermudez Salazar"                @R_403_6818@_name: "My Watch @R_403_6818@"            }          ],    created: "2011-04-16 11:00:08"}
@H_502_0@如您所见,与信息字段关联的结构是不同的.有时是对象,有时是数组.不出所料,GSON库在解析时会引发错误.
您知道当字段更改结构时如何解析JsON结构吗?

@H_502_0@谢谢你的帮助.

解决方法:

@H_502_0@使用Gson的当前解决方案有些复杂,需要实现自定义实例创建器和/或自定义反序列化器.有关详细信息,请查看@L_419_1@和the release notes on Hierarchical Type Adapters.我刚刚发布了一个示例,它用Gson响应Polymorphism with gson进行了多态反序列化.

@H_502_0@希望Gson不久将拥有RuntimeTypeAdapter,以实现更简单的多态反序列化.有关更多信息,请参见@L_419_1@.

@H_502_0@另一方面,基于Jackson的解决方案还不错.

@H_502_0@

public class Foo{  static String Jsoninput =  "[" +     "{" +       "\"type\":\"earnings\"," +       "\"info\":" +       "{" +         "\"earnings\":64.09," +         "\"divIDends\":1277.34," +         "\"gains\":1997.05," +         "\"expenses\":4895.51," +         "\"shares_bought\":210," +         "\"shares_bought_user_count\":2," +         "\"shares_sold\":0," +         "\"shares_sold_user_count\":0" +       "}," +       "\"created\":\"2011-04-16 11:32:37\"" +     "}," +     "{" +       "\"type\":\"following\"," +       "\"info\":" +       "[" +         "{" +           "\"ticker\":\"SolPHE\"," +           "\"full_name\":\"RodrigoBermudezSalazar\"," +           "\"@R_403_6818@_name\":\"MyRecommendedBuys\"" +         "}," +         "{" +           "\"ticker\":\"SolPHE\"," +           "\"full_name\":\"RodrigoBermudezSalazar\"," +           "\"@R_403_6818@_name\":\"MyWatch@R_403_6818@\"" +         "}" +       "]," +       "\"created\":\"2011-04-16 11:00:08\"" +     "}" +   "]";  public static voID main(String[] args) throws Exception  {    ObjectMapper mapper = new ObjectMapper();    mapper.setPropertyNamingStrategy(new CamelCaseNamingStrategy());    DateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    mapper.setDateFormat(dataFormat);    Collection<Thing> things = mapper.readValue(Jsoninput, new TypeReference<Collection<Thing>>(){});    System.out.println(things);  }}@JsonTypeInfo(use=JsonTypeInfo.ID.name, include=JsonTypeInfo.As.PROPERTY, property="type")@JsonSubTypes({@Type(value=Earnings.class, name="earnings"), @Type(value=Following.class, name="following")})abstract class Thing{  private Date created;  voID setCreated(Date created)  {    this.created = created;  }  @OverrIDe  public String toString()  {    return String.format(        "[%1$s: created=%2$s, other attributes:%3$s]",        getClass().getSimplename(), created, toStringAddenda());  }  abstract String toStringAddenda();}class Earnings extends Thing{  private EarningsInfo info;  voID setInfo(EarningsInfo info)  {    this.info = info;  }  @OverrIDe  String toStringAddenda()  {    return info.toString();  }}class Following extends Thing{  private Collection<FollowingInfo> info;  voID setInfo(Collection<FollowingInfo> info)  {    this.info = info;  }  @OverrIDe  String toStringAddenda()  {    return info.toString();  }}class FollowingInfo{  private String ticker;  private String fullname;  private String @R_403_6818@name;  voID setTicker(String ticker)  {    this.ticker = ticker;  }  voID setFullname(String fullname)  {    this.fullname = fullname;  }  voID set@R_403_6818@name(String @R_403_6818@name)  {    this.@R_403_6818@name = @R_403_6818@name;  }  @OverrIDe  public String toString()  {    return String.format(        "[FollowingInfo: ticker=%1$s, fullname=%2$s, @R_403_6818@name=%3$s]",        ticker, fullname, @R_403_6818@name);  }}class EarningsInfo{  private BigDecimal earnings;  private BigDecimal divIDends;  private BigDecimal gains;  private BigDecimal expenses;  private int sharesBought;  private int sharesBoughtUserCount;  private int sharesSold;  private int sharesSoldUserCount;  voID setEarnings(BigDecimal earnings)  {    this.earnings = earnings;  }  voID setdivIDends(BigDecimal divIDends)  {    this.divIDends = divIDends;  }  voID setGains(BigDecimal gains)  {    this.gains = gains;  }  voID setExpenses(BigDecimal expenses)  {    this.expenses = expenses;  }  voID setSharesBought(int sharesBought)  {    this.sharesBought = sharesBought;  }  voID setSharesBoughtUserCount(int sharesBoughtUserCount)  {    this.sharesBoughtUserCount = sharesBoughtUserCount;  }  voID setSharesSold(int sharesSold)  {    this.sharesSold = sharesSold;  }  voID setSharesSoldUserCount(int sharesSoldUserCount)  {    this.sharesSoldUserCount = sharesSoldUserCount;  }  @OverrIDe  public String toString()  {    return String.format(        "[EarningsInfo: earnings=%1$s, divIDends=%2$s, gains=%3$s, expenses=%4$s, sharesBought=%5$s, sharesBoughtUserCount=%6$s, sharesSold=%7$s, sharesSoldUserCount=%8$s]",        earnings, divIDends, gains, expenses, sharesBought, sharesBoughtUserCount, sharesSold, sharesSoldUserCount);  }}class CamelCaseNamingStrategy extends PropertyNamingStrategy{  @OverrIDe  public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultname)  {    return convert(defaultname);  }  @OverrIDe  public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultname)  {    return convert(defaultname);  }  @OverrIDe  public String nameForFIEld(MapperConfig<?> config, AnnotatedFIEld fIEld, String defaultname)  {    return convert(defaultname);  }  private String convert(String defaultname)  {    char[] nameChars = defaultname.tochararray();    StringBuilder nameTranslated = new StringBuilder(nameChars.length * 2);    for (char c : nameChars)    {      if (Character.isUpperCase(c))      {        nameTranslated.append("_");        c = Character.tolowerCase(c);      }      nameTranslated.append(c);    }    return nameTranslated.toString();  }}
总结

以上是内存溢出为你收集整理的java-使用GSON解析没有特定结构的JSON字段全部内容,希望文章能够帮你解决java-使用GSON解析没有特定结构的JSON字段所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1094427.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存