Help needed parsing a json response with a changing key value into objects (import mapping) (REST service)

0
Hi, I have the following json response: '{ "228400": { "success": true, "val": "A","data": { "type": "game", "name": "123", "appid": 228400}}}' So the key of the first block is the appid (which differs everytime for each game/app). For now, I have not found a way to parse this object properly so the import mapping works. When I use a json structure to setup the import mapping, it only works if the key value is as defined; if other key values are used, the mapping fails.   So if the key of the json is the same as the json structure (228400), the import mapping succeeds and gives me a valid second level object. If the key differs from 228400, like 4123, it fails and returns an empty second level object. I've tried unticking the key value, but same effect: Same as unticking the object... still no valid object if the key doesn't match the json structure.   My workaround for now is to call a java action that strips the first part of the json object and only returns the data part as a valid json (as that's the only part I need). That works fine, but seems ugly and unnecessary to me, as it should be supported natively from Mendix.   I also tried using message definitions, but as there are some other json arrays that will not parse with message definitions (the json example is just a bare minimum example) and message definitions don't go well with unindexed arrays.   So anyone has a clue how to make this work?  
asked
4 answers
0

I don't think this is valid JSON. The app id is used where you'd expect a fixed object or attribute name. Maybe I'd change the response first. You could use the RegexReplaceAll java action in CommunityCommons:

Haystack: your JSON content string

Needle: ("\d+")(.*)

Replacement: "YourFixedAppIdAttributeName":$1,"RandomObjectName"$2

This should replace the first quoted number, so you can import that to an attribute and then import the rest to an associated object. After replacement the json should look like this:

{ "YourFixedAppIdAttributeName":"228400",

"RandomObjectName":{

  "success":true,

etc

answered
0

Mendix JSON import mappings currently do not support this type of JSON construct. Best option is to transform the JSON message into a JSON message that is supported using a java json transformation library. You could wrap this functionality in a custom java action to make it easy to use in a microflow.

 

2 libraries that i have used successfully are Josson and JSLT2:

 

* https://github.com/octomix/josson

* https://github.com/tonysparks/jslt2

answered
0

Yes it is valid, in the past you could this with the Rest Services module, see this answer

answered
0

The marketplace module JsonVariableKeysToArray offers a Java action to transform a JSON string that contains variable keys into a JSON array, because variable keys can't be managed by the import mapping of Mendix.

answered