Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSONUtility.toModel(): add support for parsing maps #1350

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
*******************************************************************************/
package org.eclipse.jdt.ls.core.internal;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.lsp4j.jsonrpc.json.MessageJsonHandler;

Expand Down Expand Up @@ -61,6 +63,18 @@ private static <T> T toModel(Gson gson, Object object, Class<T> clazz) {
if (object instanceof String) {
return gson.fromJson((String) object, clazz);
}
if (object instanceof Map) {
try {
Map<String, Object> map = (Map<String, Object>) object;
T result = clazz.newInstance();
for (Field field : clazz.getFields()) {
field.set(result, map.get(field.getName()));
}
return result;
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,12 @@

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.lsp4j.Position;
import org.junit.Test;

Expand Down Expand Up @@ -54,4 +58,21 @@ public void testNullObject(){
assertNull(JSONUtility.toModel(null, Object.class));
}

private static class Options {
public String option1;
public String option2;
}

@Test
public void testMap() {
Map<String, Object> map = new HashMap<>();
map.put("option1", "value1");
map.put("option2", "value2");

Options options = JSONUtility.toModel(map, Options.class);
assertNotNull(options);
assertEquals(options.option1, "value1");
assertEquals(options.option2, "value2");
}

}