How to create a JSON string using a key / value on a map

I am trying to create a JSON string using the corresponding key / value pair. In the code below, I am trying to iterate over an AttributeValue list, and then I am trying to customize a JSON string using al.getValue map .

 private <T> String createJsonWithEscCharacters(List<AttributeValue<T>> list) { StringBuilder keyValue = new StringBuilder(); if (list != null) { for (AttributeValue<?> al: list) { keyValue.append("\"").append("v").append("\"").append(":").append(" {"); for (Map.Entry<String, String> entry : ((Map<String, String>) al.getValue()).entrySet()) { keyValue.append("\"").append(entry.getKey()).append("\""); keyValue.append(":").append(" \"").append(entry.getValue()).append("\"").append(","); System.out.println(keyValue); } } } return null; } 

When I check al , I see value as LinkedHashMap<K,V> , and when I type al.getValue() , it gives me this -

 {predictedCatRev=0;101;1,1;201;2, predictedOvrallRev=77;2,0;1,16;3, sitePrftblty=77;2,0;1671679, topByrGms=12345.67, usrCurncy=1, vbsTopByrGmb=167167.67} 

So this means that I can repeat the al.getValue() map and use those key/value pair to create a JSON string.

Now I'm trying to make a JSON string, map iteration al.getValue() . So the JSON string should look something like this after repeating the map al.getValue() -

 { "lv": [ { "v": { "predictedCatRev": "0;101;1,1;201;2", "predictedOvrallRev": "77;2,0;1,16;3", "sitePrftblty": "77;2,0;1671679", "topByrGms": "12345.67", "usrCurncy": "1", "vbsTopByrGmb": "167167.67" } } ], } 

I am wondering what is the cleanest way to do this? In my code above, I cannot fully execute the JSON String described above, but no matter what code I have above, it can make a small part of the JSON String the way I needed, but not the full JSON String in the path, I'm in search. Can someone help me with this, how will this be the cleanest way to do this?

thanks

+4
source share
5 answers

You do not know what kind of task you are working on, but there are many JSON libraries for Java that can do this for you, for example json in java and google-gson . For example, in json in java, once you have filled all the values ​​in a JSONObject , converting it to a JSON string is pretty simple:

 JSONObject.toString(); // compact JSON string JSONObject.toString(int indent); // easier readable format with indention. 

For example, in your case, you can create a JSONObject as follows and call its toString () function. This can protect your time from format string to JSON format:

 JSONObject jsonObject = new JSONObject(); Map<String, String> strStrMap = new HashMap<String, String>(); strStrMap.put("hello", "world"); strStrMap.put("here is", "an example"); jsonObject.put("myMap", strStrMap); System.out.println(jsonObject.toString(2)); 

and here is his conclusion:

 {"myMap": { "hello": "world", "here is": "an example" }} 
+3
source

You can just do something like this:

 import org.json.JSONObject; JSONObject rootJo = new JSONObject(); for (AttributeValue<?> al : list) { JSONObject mapJo = new JSONObject(al.getValue()); rootJo.put("v", mapJo); } 

In other words:

  • create a new (empty) JSONObject named rootJo (root JSON object)
  • map list iteration
  • for each item in the list, convert the map to a JSONObject (using the library)
  • add new rootJo property (key will be v )
  • set v to the JSONObject that was created from the map

Maybe I missed something, but I would replace your whole method with the following:

 /** * Creates a JSON object from a list of attributes that * have maps as their values. */ private JSONObject toJson(List<AttributeValue<?>> attList) { if (attList == null) { return null; } JSONObject jo = new JSONObject(); JSONArray ja = new JSONArray(); for (AttributeValue<?> att : attList) { JSONObject mapJo = new JSONObject(att.getValue()); ja.put("v", mapJo); } jo.put("lv", ja); return jo; } 

You should also make it typical, but I will leave you finer details ...

(plus I'm not sure if the AttributeValue attribute ... cannot find it anywhere)

+3
source

Use Jackson. It is light and fast than Gson. It is also not known to come bundled with OEMs, which can ruin your class path.

+2
source

When using google gson.

 var getRowData = [{ "dayOfWeek": "Sun", "date": "11-Mar-2012", "los": "1", "specialEvent": "", "lrv": "0" }, { "dayOfWeek": "Mon", "date": "", "los": "2", "specialEvent": "", "lrv": "0.16" }]; JsonElement root = new JsonParser().parse(request.getParameter("getRowData")); JsonArray jsonArray = root.getAsJsonArray(); JsonObject jsonObject1 = jsonArray.get(0).getAsJsonObject(); String dayOfWeek = jsonObject1.get("dayOfWeek").toString(); 

// when using jackson

  JsonFactory f = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(); JsonParser jp = f.createJsonParser(getRowData); // advance stream to START_ARRAY first: jp.nextToken(); // and then each time, advance to opening START_OBJECT while (jp.nextToken() == JsonToken.START_OBJECT) { Map<String,Object> userData = mapper.readValue(jp, Map.class); userData.get("dayOfWeek"); // process // after binding, stream points to closing END_OBJECT } 
+1
source

I assume that you want to send JSON back in response to a call request. You can use the Spring framework, where it automatically converts the Map object to JSON using the Jackson converter. You will just need to use the @ResponseBody annotation for the return type. You can read more about Spring 3 documentation.

0
source

Source: https://habr.com/ru/post/1486134/


All Articles