如何使用Map中的键/值创建JSON字符串

时间:2022-10-26 16:28:00

I am trying to create a JSON String using the corresponding key/value pair. In the below code, I am trying to iterate the list of AttributeValue and then I am trying to makie the JSON String using the al.getValue map.

我试图使用相应的键/值对创建一个JSON字符串。在下面的代码中,我试图迭代AttributeValue列表,然后我尝试使用al.getValue映射makie JSON字符串。

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 inspect on al, I see value as LinkedHashMap<K,V> and when I print al.getValue(), it gives me this-

当我检查al时,我看到了LinkedHashMap 的值,当我打印al.getValue()时,它给了我这个 - ,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}

So that means, I can iterate the al.getValue() map and use those key/value pair to make the JSON String.

这意味着,我可以迭代al.getValue()映射并使用这些键/值对来生成JSON字符串。

Now I am trying to make a JSON String by iterating the al.getValue() map. So the JSON String should look something like this after iterating the al.getValue() map-

现在我试图通过迭代al.getValue()映射来创建一个JSON字符串。因此,在迭代al.getValue()映射之后,JSON String应该看起来像这样 -

{
 "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 above code, I am not fully able to make the above JSON String but whatever code I have above, it is able to make slight portion of JSON String in the way I needed but the not full JSON String in the way, I am looking for. Can anyone help me on this like what will be the cleanest way to do this?

我想知道最干净的方法是什么?在我的上面的代码中,我不能完全能够制作上面的JSON字符串,但无论我上面的代码是什么,它都能够以我需要的方式制作一小部分JSON字符串,但是方式中不是完整的JSON字符串,我是寻找。任何人都可以帮助我,这将是最干净的方式吗?

Thanks

5 个解决方案

#1


3  

Not sure what exact task you're working, but there are many JSON libraries for Java which can do this for you such as json in java and google-gson. For example, in json in java, once you have filled all the values in its JSONObject, then converting it into JSON string is fairly easy:

不知道你正在做什么确切的任务,但有很多Java的JSON库可以为你做这些,比如java和google-gson中的json。例如,在java中的json中,一旦填充了JSONObject中的所有值,然后将其转换为JSON字符串就相当容易:

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

For example, in your case, you may create a JSONObject like the following and invoke its toString() function. This can safe your time from formatting string to fit the JSON format:

例如,在您的情况下,您可以创建如下所示的JSONObject并调用其toString()函数。这样可以节省您格式化字符串以适应JSON格式的时间:

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 its output:

这是它的输出:

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

#2


3  

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)
  • 创建一个名为rootJo的新(空)JSONObject(根JSON对象)

  • iterate over your list of maps
  • 迭代你的地图列表

  • for each element in the list, convert the map into a JSONObject (using a library)
  • 对于列表中的每个元素,将映射转换为JSONObject(使用库)

  • add a new property to rootJo (the key will be v)
  • 向rootJo添加一个新属性(密钥将为v)

  • set the value of v to the JSONObject that was created from the map
  • 将v的值设置为从映射创建的JSONObject

Maybe I'm missing something, but I would replace your entire method with this:

也许我错过了什么,但我会用这个替换你的整个方法:

/**
 *  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 typesafe, but I'll leave the finer details to you...

你也应该把它变成类型安全的,但我会给你留下更精细的细节......

(plus I'm not sure what an AttributeValue is... can't find it anywhere)

(加上我不确定什么是AttributeValue ...无法在任何地方找到它)

#3


2  

Use Jackson. It's lightweight and faster than Gson. It also isn't known to be bundled by OEMs, which can mess with your classpath.

使用杰克逊。它比Gson重量轻,速度快。它也不为OEM所捆绑,因为它可能会破坏你的类路径。

#4


1  

When using google gson.

使用谷歌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
        }

#5


0  

I am assuming that you want to send a JSON back as a response to the calling request.. You could use the Spring framework where it automatically converts the Map object to JSON using Jackson converter. You will need to just use the annotation @ResponseBody for the return type. You can read more on the Spring 3 documentation.

我假设你想要发送一个JSON作为对调用请求的响应。你可以使用Spring框架,它使用Jackson转换器自动将Map对象转换为JSON。您只需要使用注释@ResponseBody作为返回类型。您可以在Spring 3文档中阅读更多内容。

#1


3  

Not sure what exact task you're working, but there are many JSON libraries for Java which can do this for you such as json in java and google-gson. For example, in json in java, once you have filled all the values in its JSONObject, then converting it into JSON string is fairly easy:

不知道你正在做什么确切的任务,但有很多Java的JSON库可以为你做这些,比如java和google-gson中的json。例如,在java中的json中,一旦填充了JSONObject中的所有值,然后将其转换为JSON字符串就相当容易:

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

For example, in your case, you may create a JSONObject like the following and invoke its toString() function. This can safe your time from formatting string to fit the JSON format:

例如,在您的情况下,您可以创建如下所示的JSONObject并调用其toString()函数。这样可以节省您格式化字符串以适应JSON格式的时间:

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 its output:

这是它的输出:

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

#2


3  

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)
  • 创建一个名为rootJo的新(空)JSONObject(根JSON对象)

  • iterate over your list of maps
  • 迭代你的地图列表

  • for each element in the list, convert the map into a JSONObject (using a library)
  • 对于列表中的每个元素,将映射转换为JSONObject(使用库)

  • add a new property to rootJo (the key will be v)
  • 向rootJo添加一个新属性(密钥将为v)

  • set the value of v to the JSONObject that was created from the map
  • 将v的值设置为从映射创建的JSONObject

Maybe I'm missing something, but I would replace your entire method with this:

也许我错过了什么,但我会用这个替换你的整个方法:

/**
 *  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 typesafe, but I'll leave the finer details to you...

你也应该把它变成类型安全的,但我会给你留下更精细的细节......

(plus I'm not sure what an AttributeValue is... can't find it anywhere)

(加上我不确定什么是AttributeValue ...无法在任何地方找到它)

#3


2  

Use Jackson. It's lightweight and faster than Gson. It also isn't known to be bundled by OEMs, which can mess with your classpath.

使用杰克逊。它比Gson重量轻,速度快。它也不为OEM所捆绑,因为它可能会破坏你的类路径。

#4


1  

When using google gson.

使用谷歌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
        }

#5


0  

I am assuming that you want to send a JSON back as a response to the calling request.. You could use the Spring framework where it automatically converts the Map object to JSON using Jackson converter. You will need to just use the annotation @ResponseBody for the return type. You can read more on the Spring 3 documentation.

我假设你想要发送一个JSON作为对调用请求的响应。你可以使用Spring框架,它使用Jackson转换器自动将Map对象转换为JSON。您只需要使用注释@ResponseBody作为返回类型。您可以在Spring 3文档中阅读更多内容。