2

Server layer will return a list of String value, like

{"Bob", "Charlotte", "Johnson", "David"...}

Now we need the List String to be a Json object to push to front end, like

[{id: "Bob"}, {id: "Charlotte"}, {id: "Johnson"}, {id: "David"...}]

or

[{name: "Bob"}, {name: "Charlotte"}, {name: "Johnson"}, {name: "David"...}]

Any label is fine, we just need a label to make it as JSON object. Does Jackson has something to convert List of String by default i.e. {string: "Bob"}? That will be really sweet......

3
  • 1
    We are using Jackson to convert lists of Objects (sometimes even Strings). By default it converts the List<String> to an array of strings by itself. As mentioned below, if you really want it to convert to an array of name/value pairs, you should return a list of objects with one String name (or id or whatever) property. Commented May 15, 2013 at 1:38
  • @Shadow Creeper Thanks, that's great, but if the converted array of string doesn't have a label, then how can the front end identify the value(as JSON object), especially want a label to handle list? Commented May 15, 2013 at 1:47
  • 1
    Our front end is a simple web app. We just iterate through the list. You can sort the list if you like, or add to it, remove from it, modify it. It is just an array, with a length and everything. You can do the normal for loop and reference it via resultArray[index]. Commented May 15, 2013 at 1:52

2 Answers 2

7

The easiest thing to is to make your controller method return a structure that maps exactly to the JSON you want - for example a List<SomeObject> where SomeObject is a class with a String id field.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Like you said I made an inner class with only one String field to hold the value, then made a list of this class object. Now it can be identified from front end.
1

Th way of doing this is converting you List of String into a New Map.

Code :

@ResponseBody
@RequestMapping("/mapping")
function mySpring()
{


            List<String> myStringList;
            Map<String,String> jsonMap= new LinkedHashMap<String,String>(); 
     // Use LinkedHashMap if you want to maintain order


    String key="id";        
     // Id or Name

            for (String myString: myStringList)
        {
        jsonMap.put(key,myString);

        }

return jsonMap;

}

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.