将完整对象转换为JSON

huangapple go评论76阅读模式
英文:

Convert complete object to JSON

问题

你好,我有一个类似这样的类:

public class A {
    String x;
    String y;
    String data;
}

变量 x 和 y 包含普通字符串,但变量 data 包含一个 JSON 字符串,即:

x = "aaaa";
y = "bbbb";
data = "{\"key\":\"val\"}";

我想将整个对象转换为 JSON,使最终输出如下:

{
    "x": "aaaa",
    "y": "bbbb",
    "data": {
        "key": "val"
    }
}

我尝试使用 new JSONObject(object) 将对象转换为 JSON。这对于 xy 属性效果很好,但 data 仍然保持为这样的字符串:

"data": "{\"key\":\"value\"}"

我希望 data 也可以一次性转换为 JSON。如何实现这一点?

英文:

Hi I have a class like this :

public class A {
String x;
String y;
String data;
}

The variables x and y contain normal Strings but variable data contains a JSON string, i.e, '

x = "aaaa";
y = "bbbb";
data = "{\"key\":\"val\"}";

I want to convert the complete object in JSON such that final output is :

{
x : "aaaa",
y : "bbbb",
data : {
      "key" : "val"
       }
}

I tried using new JSONObject(object) to convert the object to JSON. It does fine for x and y attributes but the data remains as a String like this :

data : "{\\\"key\\\":\\\"value\\\"}"

. I want data to be JSONified as well in one go.

How to implement this?

答案1

得分: 5

最简单的方法是让你的 data 字段成为另一个对象。

public class Data {

   String key;
   String val;
}

并且在你的类中:

public class A { //Java 类名以大写字母开头

   String x;
   String y;
   Data data;
}
英文:

The simplest way is having your data field be another object.

public class Data {

   String key;
   String val;
}

and in your class;

public class A { //Java classes start with uppercase

   String x;
   String y;
   Data data;
}

答案2

得分: 0

public class Main {

  public static void main(String[] args) {

    a obj = new a();
    obj.x = "aaaa";
    obj.y = "bbbb";
    obj.data = "{\"key\":\"val\"}";

    String str = new JSONObject(obj).toString().replaceAll("\\\\", "")
            .replaceAll("\"\\{", "{")
            .replaceAll("\\}\"", "}");
    System.out.println(str);
  }
}

output:

{"data":{"key":"val"},"x":"aaaa","y":"bbbb"}

or you can use org.apache.commons.text.StringEscapeUtils.unescapeJson to do the work easily.

英文:

If you don't want to modify the class or create new class extending from it, You can just remove unnecessary characters:

public class Main {

  public static void main(String[] args) {

    a obj = new a();
    obj.x = "aaaa";
    obj.y = "bbbb";
    obj.data = "{\"key\":\"val\"}";

    String str = new JSONObject(obj).toString().replaceAll("\\\\", "")
            .replaceAll("\"\\{", "{")
            .replaceAll("\\}\"", "}");
    System.out.println(str);
  }
}

output:

{"data":{"key":"val"},"x":"aaaa","y":"bbbb"}

or you can use org.apache.commons.text.StringEscapeUtils.unescapeJson to do the work easily.

答案3

得分: 0

根据 Doga Oruc 的回答,鉴于 OP 的响应,这里有一个解决方法:从成员数据中读取您的字符串,然后使用 JsonObject 类将该 JSON 字符串解析为 Map<String, Object>。然后将您的 A 类解析为 JSON,再将其解析回 Map<String, Object>。在第二个映射中,用第一个映射的值替换键 "data"。这显然很繁琐,但这是无法修改原始类的代价。

英文:

Given OP response to Doga Oruc answer here is a workaround: Read your String from member Data and parse that JSON string to Map&lt;String, Object&gt; using JsonObject class. Then parse your class A to JSON and parse it back to Map&lt;String, Object&gt;. In that second map replace key "data" with the value of your first map. This is obviously cumbersome, but that's the price for not being able to modify your original class

答案4

得分: 0

    class AWrapper {
        String x;
        String y;
        Object data;

        public AWrapper(A a, ObjectMapper mapper) throws IOException {
            this.x = a.x;
            this.y = a.y;
            this.data = mapper.readValue(a.data, Object.class);
        }

        public String getX() {
            return x;
        }
        public String getY() {
            return y;
        }
        public Object getData() {
            return data;
        }
    }

    class SomeClass {
        public static String toJson(A a) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            AWrapper aWrapper = new AWrapper(a, mapper);
            return mapper.writeValueAsString(aWrapper);
        }
    }
英文:

How about something like this with Jackson?

    class AWrapper {
        String x;
        String y;
        Object data;

        public AWrapper(A a, ObjectMapper mapper) throws IOException {
            this.x = a.x;
            this.y = a.y;
            this.data = mapper.readValue(a.data, Object.class);
        }

        public String getX() {
            return x;
        }
        public String getY() {
            return y;
        }
        public Object getData() {
            return data;
        }
    }

    class SomeClass {
        public static String toJson(A a) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            AWrapper aWrapper = new AWrapper(a, mapper);
            return mapper.writeValueAsString(aWrapper);
        }
    }

huangapple
  • 本文由 发表于 2020年9月10日 17:43:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63827004.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定