使用Gson从JSOn对象中读取每一行

时间:2013-06-23 14:34:55

标签: java json api parsing gson

我有一个Java项目,我必须从JSON输入构建一个对象,它有以下格式:

{
  "Shell": 13401,
  "JavaScript": 2693931,
  "Ruby": 2264,
  "C": 111534,
  "C++": 940606,
  "Python": 39021,
  "R": 2216,
  "D": 35036,
  "Objective-C": 4913
}

然后在我的代码中我有:

public void fetchProjectLanguages(Project project) throws IOException {
    List<Language> languages = null;

    String searchUrl = String.format("%s/repos/%s/%s/languages",
            REPO_API, project.getUser().getLogin(), project.getName());

    String jsonString = requests.get(searchUrl);
    Language lang = gson.fromJson(jsonString, Language.class);

    languages.add(lang);
}

我的Language对象由两个属性组成:nameloc,而JSON输入本身并不代表语言,而是语言,作为对象的每一行语言本身。在我的例子中:shell,javascript,ruby,c,c ++,python,R,D和Objective-C。

怎么能这样做?

我感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

您可以使用 adapter

说你有:

class Language
{
    public String name;
    public Integer loc;
}

class Languages
{
    public List<Language> list = new ArrayList<Language>();
}

适配器:

class LanguagesTypeAdapter implements JsonSerializer<Languages>, JsonDeserializer<Languages>
{
      public JsonElement serialize(Languages languages, Type typeOfT, JsonSerializationContext context)
      {
          JsonObject json = new JsonObject();

          for (Language language : languages.list)
          {
              json.addProperty(language.name, language.loc);
          }

          return json;
      }

      public Languages deserialize(JsonElement element, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
      {
          JsonObject json = element.getAsJsonObject();

          Languages languages = new Languages();

          for (Entry<String, JsonElement> entry : json.entrySet())
          {
              String name = entry.getKey();
              Integer loc = entry.getValue().getAsInt();

              Language language = new Language();
              language.name = name;
              language.loc = loc;

              languages.list.add(language); 
          }

          return languages;
      }
}

一个样本:

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Languages.class, new LanguagesTypeAdapter());

Gson gson = builder.create();

Languages languages = gson.fromJson("{"+
          "\"Shell\": 13401,"+
          "\"JavaScript\": 2693931,"+
          "\"Ruby\": 2264,"+
          "\"C\": 111534,"+
          "\"C++\": 940606,"+
          "\"Python\": 39021,"+
          "\"R\": 2216,"+
          "\"D\": 35036,"+
          "\"Objective-C\": 4913"+
        "}", Languages.class);

String json = gson.toJson(languages);

结果:

{"Shell":13401,"JavaScript":2693931,"Ruby":2264,"C":111534,"C++":940606,"Python":39021,"R":2216,"D":35036,"Objective-C":4913}

希望这会有所帮助......

答案 1 :(得分:0)

您可以尝试Map<String, String> map = gson.fromJson(json, new TypeToken<Map<String, String>>() {}.getType());来获取语言/值的地图。