|
Re: Recycling non EMF-aware web services [message #1591575 is a reply to message #1587709] |
Thu, 29 January 2015 16:13 |
Thomas Elskens Messages: 159 Registered: September 2014 Location: Brussels - Belgium |
Senior Member |
|
|
Okay it turns out that with EMF's reflective capabilities, creating a custom JSON parsing mechanism is really only a matter of a few lines of code (and some solid naming conventions).
The code is not optimized and not very pretty, but the basic idea is conveyed (with Jackson library) :
//...
public List<EObject> readJSonAsList(String jsonString, String rootType) throws IOException
{
List<EObject> result = new ArrayList<>() ;
JsonNode root = mapper.readTree(jsonString) ;
if (root.getNodeType() != JsonNodeType.ARRAY) throw new IOException("Wrong data format : ARRAY expected !") ;
Iterator<JsonNode> elements = root.iterator() ;
while (elements.hasNext())
{
JsonNode arrayNode = elements.next() ;
EObject arrayElement = recursiveReading(rootType,arrayNode) ;
result.add(arrayElement) ;
}
return result ;
}
private EObject recursiveReading(String fieldName, JsonNode root) throws IOException
{
EClass clazz = getEClass(fieldName) ;
EObject result = clazz.getEPackage().getEFactoryInstance().create(clazz) ;
Iterator<Entry<String,JsonNode>> fields = root.fields() ;
while (fields.hasNext())
{
Entry<String,JsonNode> field = fields.next() ;
String nextFieldName = field.getKey() ;
JsonNode nextNode = field.getValue() ;
if (nextNode.getNodeType() == JsonNodeType.OBJECT)
{
result.eSet(clazz.getEStructuralFeature(nextFieldName), recursiveReading(nextFieldName,nextNode));
}
else
{
setField(result, nextFieldName, nextNode) ;
}
}
return result ;
}
//...
Sorry for bothering !
|
|
|
Powered by
FUDForum. Page generated in 0.02590 seconds