-2

I want to convert Map<String,String> to Custom Json output e.g: My Map have data like

--------
ID |Desc
--------
1  | A
2  | B
3  | C

My Json should out put above map with custom keys i.e. ID & Desc:

[{id:1,desc,A},{id:2,desc,B},{id:3,desc,C}]

Earlier I have used List to convert to Json using object classes:

List<CustomObject> myList = new ArrayList<>();

ObjectMapper mapper = new ObjectMapper();
String jsonText = mapper.writeValueAsString(myList);

so this converts to what ever fields i have in CustomObject Class. But as Map just have key/values and no fieldnames, so i need to know how i can set them.

AxelH
  • 14,325
  • 2
  • 25
  • 55
usman
  • 1,351
  • 5
  • 23
  • 47
  • 2
    Write some code? That would be a good start. If you're looking for a library to do this, that's [off topic](https://stackoverflow.com/help/on-topic) on this site. If you want us to write some code for you, that is too. You need do some research, try and come up with a solution, and then - if solution doesn't work - come back here with that and ask for help. We expect [**much more**](http://meta.stackoverflow.com/a/261593/2071828) effort from you. Much more. – Boris the Spider Jan 19 '17 at 11:35
  • Updated Question with code being used. where org.codehaus.jackson jackson-jaxrs lib is used – usman Jan 19 '17 at 11:46
  • Now, you can google "Jackson serialize `Map`" and go through the several answers on this site and tutorials on the Internet. **Do some research**. – Boris the Spider Jan 19 '17 at 11:49
  • Have you google it ? It seems you need a guide. 10s search gave [an external guide](http://websystique.com/java/json/jackson-convert-java-map-to-from-json/) – AxelH Jan 19 '17 at 11:49
  • yup, looking into http://stackoverflow.com/questions/11628698/can-we-make-object-as-key-in-map-when-using-json – usman Jan 19 '17 at 11:50

1 Answers1

0

Optimize and enjoy

//*******************************************************************
// NOTE: please read the 'More Info' tab to the right for shortcuts.
//*******************************************************************

import java.lang.Math; // headers MUST be above the first class
import java.util.*;

// one class needs to have a main() method
public class MapToJson
{
 // arguments are passed using the text field below this editor
 public static void main(String[] args)
 {
   Map<String,String> map = new HashMap<>();
   map.put("1","A");
   map.put("2","B");
   map.put("3","C");

   final StringBuilder string = new StringBuilder("[");    


   map.forEach((k,v)->string.append("{id:"+k+",desc"+v+"},"));


   string.append("]");


   System.out.println(string.toString());

  }


 }