1

I have the following as part of a method that is basically grabbing a webpage, I want to map the resulting header and body to JSON, the body is spat out as a string but ideally I want the header values split into key value so in the JavaScript I can access them directly.

Map<String, String> assoc = new HashMap<String, String>();

Map<String, List<String>> headerMap = new LinkedHashMap<String, List<String>>();
headerMap = connection.getHeaderFields();

for (String key : headerMap.keySet()) {
    assoc.put(key, headerMap.get(key).toString());
}

JSONObject returnObj = new JSONObject();
returnObj.put("header", assoc);
returnObj.put("body", sb.toString());

return returnObj.toString(); //Set digit to add indent spacing.

This unfortunately returns the header as a string rather than an array...

{"header":"{cache-control=[max-age=0], content-type=[text\/html], connection=[Keep-Alive],

Ideally this would be more like (friendlier for javascript)...

{
    "headers": [
        {"test": "testval"},
        {"testb": "testbval"}
    ]
}

2 Answers 2

3
JSONObject returnObj = new JSONObject();
for (String key : headerMap.keySet()) {
    returnObj.put(key, headerMap.get(key).toString());
}
return returnObj.toString();

I have not used this api before, but from the javadoc I am pretty sure the code above will give you what you want. Since you are only dealing with one set of data (the header object), this method will work. If you had many objects, you would have to do something different. Try flexjson, that is one I use often.

Also, the reason you are getting your current output is the JSONObject.put is calling the Map's toString() which produces a string of all key/value pairs represented as "key=value" separated by a comma and wrapped in curly brackets.

{"key1=value1", "key2=value2", etc..}
Sign up to request clarification or add additional context in comments.

Comments

0

I think you are probably looking for

{"header":[
             {"cache-control=[max-age=0]"},
             {"content-type=[text\/html]"},
             {"content-type=[text\/html]"}
          ]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.