JavaScript无法解析用Java从Gson序列化的字符串 [英] JavaScript unable to parse string serialized with Gson from Java

查看:228
本文介绍了JavaScript无法解析用Java从Gson序列化的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是这个问题的重复,因为这里的问题是关于从Java中序列化的JSON字符串的表示字面形式在JavaScript中(它不止是双引号)。

我在Java中使用 Gson ,我随后无法使用JavaScript内部化 JSON.parse 。当我在Java对象中使用双引号时,会发生这种情况。我发现,Gson应该照顾正确的转义,而JSON序列化格式是语言无关的,所以当我从Java序列化时,我应该能够从JavaScript反序列化而不会有任何麻烦。



以下最小代码:

Java序列化



  import java.util。*; 
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

class LOV {
List< String>值;

public LOV(List< String> values){
this.values = values;



public class FooMain {

private static final Gson gson = new GsonBuilder()。serializeNulls()。create();

@SuppressWarnings(unchecked)
public static< T> T fromJson(String json,Class< T> classOfT){
T target =(T)gson.fromJson(json,(Type)classOfT);
回报目标;
}

public static void main(String args []){
List< String> values = new ArrayList<>();
values.add(\foo \);
LOV lov =新的LOV(值);
String s = gson.toJson(lov);
System.out.printf(Stringified JSON is:[%s] \\\
,s);
LOV lov2 = fromJson(s,LOV.class);
}
}

…上面的代码显示序列化和反序列化是可能的并且可行。我还为LOV类写了一个 equals 方法来确定重新内化的对象( lov2 )等于(原本是序列化的)(也就是说,我只是跳过这段代码来保持这个简短)。



上面的代码打印在控制台上:

 字符串化的JSON是:[{values:[\foo \]}] 
  JSON.parse('{values:[\foo \]}' ); 

…我得到:
$ b $ pre $ 未捕获的SyntaxError:JSON在位置13处的意外的标记f(...)

  s.replace(\\, \\\\)
s.replace(\,\\\\)
s.replace(',\\\ \\')

…在JavaScript方面,我也必须这样做:

$ p $ JSON.parse('由Java'.replace(' / \ t / g,\\t));

这是行得通的,但变得越来越复杂,我不确定我是否覆盖了所有案例我刚刚使用 StringEscapeUtils.escapeEcmaScript 的结尾,它的功能就像一个魅力。在JavaScript端使用 escapeEcmaScript 一个简单的 JSON.parse('由Java准备的字符串')就足够了。

解决方案

您需要为Javascript的 JSON.parse 使用双反斜杠。这应该工作:



JSON.parse('{values:[\\foo\\] }');



这是因为您还需要转义反斜杠。


This is not a duplicate of this question as the question here is specifically about representation of JSON strings serialized from Java in literal form in JavaScript (and it's more than double quotes one has to worry about).

I am creating in Java a serialized JSON object using Gson which I am subsequently unable to internalize from Javascript using JSON.parse. This occurs when I have escaped double quotes in my Java object. I find that baffling as Gson is supposed to take care of proper escaping and the JSON serialization format is language-agnostic so when I serialize from Java I should be able to deserialize from JavaScript without any headaches.

Minimal code below:

Java serialization

import java.util.*;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

class LOV {
    List<String> values;

    public LOV(List<String> values) {
        this.values = values;
    }
}

public class FooMain {

    private static final Gson gson = new GsonBuilder().serializeNulls().create();

    @SuppressWarnings("unchecked")
    public static <T> T fromJson(String json, Class<T> classOfT) {
        T target = (T) gson.fromJson(json, (Type) classOfT);
        return target;
    }

    public static void main(String args[]) {
        List<String> values = new ArrayList<>();
        values.add("\"foo\"");
        LOV lov = new LOV(values);
        String s = gson.toJson(lov);
        System.out.printf("Stringified JSON is: [%s]\n", s);
        LOV lov2 = fromJson(s, LOV.class);
    }
}

… the above code shows that serialization and deserialization is possible and works. I also wrote an equals method for the LOV class to establish that the re-internalized object (lov2) is equal to the originally serialized one (and it is, I am just skipping this code to keep this short).

The above code prints on the console:

Stringified JSON is: [{"values":["\"foo\""]}]

JavaScript internalization

Yet, when I am trying to internalize in JavaScript the string created by Java:

JSON.parse('{"values":["\"foo\""]}');

… I get:

Uncaught SyntaxError: Unexpected token f in JSON at position 13(…)

Resolution

In the end, based on the accepted answer and the commentary to it I automatically escaped a number of characters in the Java side but there were many cases to consider. So I had to do (in Java) all of the following:

s.replace("\\", "\\\\")
s.replace("\"", "\\\"")
s.replace("'", "\\'")

… and on the JavaScript side I also had to do:

JSON.parse('the string literal prepared by Java'.replace(/\t/g, "\\t"));

This is working but is getting complicated and I wasn't sure I had all the cases covered so in the end I just used StringEscapeUtils.escapeEcmaScript and it worked like a charm. Using escapeEcmaScript a simple JSON.parse('the string literal prepared by Java') was sufficient on the JavaScript side.

解决方案

You need to use double backslash for Javascript's JSON.parse. This should work:

JSON.parse('{"values":["\\"foo\\""]}');

This is because you also need to escape the backslash.

这篇关于JavaScript无法解析用Java从Gson序列化的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆