简体   繁体   English

将PHP关联数组传输到Java Map <String, Double> 使用JSON(GSON)

[英]Transfer PHP associative array to Java Map<String, Double> using JSON (GSON)

I'm using PHP to return a JSON encoded associative array to a client. 我正在使用PHP将JSON编码的关联数组返回给客户端。 The array is constructed by looping through the result set of a MySQL database query. 通过遍历MySQL数据库查询的结果集来构造数组。 For simplicity's sake, instead of showing all the code that returns the result set, let's say that one possible output to the query produces the following associative array in PHP: 为简单起见,假设不显示返回结果集的所有代码,而是将查询的一个可能输出生成以下PHP关联数组:

$ResultRows = array(
    "10 m" => 10,
    "100 m" => 100,
    "1000 m" => 1000
);

echo json_encode($ResultRows);

The JSON string produced by json_encode looks like this: json_encode生成的JSON字符串如下所示:

{"10 m":10,"100 m":100,"1000 m":1000}

As you can see, it gets encoded like an object with each key-value pair looking like a property name and value. 如您所见,它像对象一样被编码,每个键值对看起来像属性名称和值。

Now, the client running Java receives this JSON encoded string. 现在,运行Java的客户端将收到此JSON编码的字符串。 I would like to create an instance of LinkedHashMap<String, Double> that is populated by these values. 我想创建一个由这些值填充的LinkedHashMap<String, Double>的实例。 However, since it is not encoded like an array, I'm having a hard time seeing how to use GSON to decode this. 但是,由于它不是像数组那样编码的,所以我很难理解如何使用GSON对此进行解码。 Any ideas? 有任何想法吗?

I could simply change the PHP and create a simple object that holds the Key/Value pairs and return a regular array of these objects, but I was hoping to leave the PHP scripts alone if possible because there are quite a few of them to change. 我可以简单地更改PHP并创建一个包含键/值对并返回这些对象的常规数组的简单对象,但是我希望尽可能地不使用PHP脚本,因为其中有很多需要更改。

You can provide a type to the fromJson method with the TypeToken class, so it would be something like this: 您可以使用TypeToken类为fromJson方法提供一种类型,因此如下所示:

public class Test {
    public static void main(String[] args) {
        String json ="{\"10 m\":10,\"100 m\":100,\"1000 m\":1000}";
        LinkedHashMap<String, Double> map = new Gson().fromJson(json, new TypeToken<LinkedHashMap<String, Double>>(){}.getType());
        System.out.println(map);
    }
}

Which output: 哪个输出:

{10 m=10.0, 100 m=100.0, 1000 m=1000.0}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM