Reputation: 8062
I have a Java project where I must build an object from a JSON input, which comes in the following format:
{
"Shell": 13401,
"JavaScript": 2693931,
"Ruby": 2264,
"C": 111534,
"C++": 940606,
"Python": 39021,
"R": 2216,
"D": 35036,
"Objective-C": 4913
}
Then in my code I have:
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);
}
My Language
object is composed of two attributes: name
and loc
, and the JSON input itself does not represent a language but a set of languages, being each line of the object a language itself. In my example: shell, javascript, ruby, c, c++, python, R, D and Objective-C.
How can it do that?
I appreciate any help!
Upvotes: 1
Views: 524
Reputation: 13396
You can use an adapter.
Say you have:
class Language
{
public String name;
public Integer loc;
}
class Languages
{
public List<Language> list = new ArrayList<Language>();
}
The adapter:
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;
}
}
And a sample:
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);
Results :
{"Shell":13401,"JavaScript":2693931,"Ruby":2264,"C":111534,"C++":940606,"Python":39021,"R":2216,"D":35036,"Objective-C":4913}
Hope this helps...
Upvotes: 1
Reputation: 2303
You can try this out Map<String, String> map = gson.fromJson(json, new TypeToken<Map<String, String>>() {}.getType());
to get a map of language/value.
Upvotes: 0