Domanda

Vorrei analizzare una risposta da parte del New York Times Search API fornite in formato JSON. Gli sguardi stringa JSON come segue (estratto):

{"facets" : 
  {"des_facet" : 
    [
      {"count" : 745 , "term" : "POLITICS AND GOVERNMENT"} , 
      {"count" : 702 , "term" : "UNITED STATES INTERNATIONAL RELATIONS"}
    ],
   "desk_facet" : 
    [
      {"count" : 2251 , "term" : "Foreign Desk"} , 
      {"count" : 242 , "term" : "Editorial Desk"}
    ]
  }
}

Sul lato Java, ho preparato il seguente gerarchia di oggetti:

public class Container {
  Facet facets;
}

public class Facet {
  Collection<Elements> des_facet;
  Collection<Elements> desk_facet;
}

public class Elements {
  private int count;
  private String term;
}

... che ovviamente non funziona. Sono nuovo di JSON. Pertanto, la struttura annidata di elementi confonde.

Grazie per il vostro aiuto!

È stato utile?

Soluzione

La struttura di classe definita corrisponde l'esempio JSON perfettamente, e deserializza senza errori per me.

// output: 
// {Container: 
//   facets=
//   {Facet: 
//     des_facet=[
//       {Elements: count=745, term=POLITICS AND GOVERNMENT}, 
//       {Elements: count=702, term=UNITED STATES INTERNATIONAL RELATIONS}
//     ], 
//     desk_facet=[
//       {Elements: count=2251, term=Foreign Desk}, 
//       {Elements: count=242, term=Editorial Desk}
//     ]
//   }
// }

import java.io.FileReader;
import java.util.Collection;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    Container container = gson.fromJson(new FileReader("input.json"), Container.class);
    System.out.println(container);
  }
}

class Container
{
  Facet facets;

  @Override
  public String toString()
  {
    return String.format("{Container: facets=%s}", facets);
  }
}

class Facet
{
  Collection<Elements> des_facet;
  Collection<Elements> desk_facet;

  @Override
  public String toString()
  {
    return String.format("{Facet: des_facet=%s, desk_facet=%s}", des_facet, desk_facet);
  }
}

class Elements
{
  private int count;
  private String term;

  @Override
  public String toString()
  {
    return String.format("{Elements: count=%d, term=%s}", count, term);
  }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top