1

我有一个 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。

它怎么能做到这一点?

我很感激任何帮助!

4

2 回答 2

1

您可以使用适配器

假设你有:

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}

希望这可以帮助...

于 2013-06-23T15:52:03.690 回答
0

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

于 2013-06-23T15:46:35.850 回答