I have a JSON File with key value pairs and I want to put the key value pairs into headers. So when I have a file with content like this:
[{"msgId": "8600C5A3-C666-4E63-BFDB-52BCF557F938", "jiraId": "ERR002"}]
I want to create headers with the name msgId and with value "8600C5A3-C666-4E63-BFDB-52BCF557F938", etc.
Or as an alternative: Is there a way to store the headers of an exchange to a file to which later on the headers can be restored in another exchange?
Thank you.
EDIT: My fork of the example.
public void jsonToHeaders(String body, @Headers Map<String, String> headers) throws ParseException {
LOG.info("Starting JSON conversion...");
LOG.debug("Body input, content: {} ", body);
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(body);
if (jsonObject != null)
{
String stringValue = null;
String stringKey = null ;
final String NA_STRING = "*** N/A ***";
for (Object key : jsonObject.keySet()) {
stringKey = ((key == null) ? NA_STRING : (String)key);
stringValue = ((jsonObject.get(stringKey) == null) ? NA_STRING : jsonObject.get(stringKey).toString());
headers.put(stringKey, stringValue);
LOG.debug("Processing key {} with value {}", stringKey, stringValue);
}
LOG.info("Done processed JSON: {}", headers.toString());
}
}
You can use bean for this case.
JSONToHeadersBean
package org.mybean;
import org.apache.camel.Headers;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class JSONToHeadersBean {
public void jsonToHeaders(String body, @Headers Map<String, String> headers) throws ParseException {
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(body);
object.keySet().forEach(key -> headers.put(key.toString(), object.get(key).toString()));
}
//for test
public static void main(String[] args) throws ParseException {
String body = "{\"msgId\": \"8600C5A3-C666-4E63-BFDB-52BCF557F938\", \"jiraId\": \"ERR002\"}";
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(body);
final Map<String, String> headers = new HashMap<String, String>();
object.keySet().forEach(key -> headers.put(key.toString(), object.get(key).toString()));
System.out.println();
}
}
Create bean
<bean class="org.mybean.JSONToHeadersBean" id="JSONToHeadersBean" name="JSONToHeadersBean"/>
And you can use it in route
<bean method="jsonToHeaders" ref="JSONToHeadersBean"/>