有没有办法将字符串和数组放在单个HashMap中?

时间:2016-04-26 19:20:33

标签: java

我正在从PHP迁移到Java。并且我试图在Java中实现类似下面的东西:

$user = array(
            "firstname" => "myname",
            "lastname" => "surname",
            "phone" => array(
                        "home" => "123213213213",
                        "office" => "312321321312312",
                        "mobile" => "4532134213131312"
                       )
       ) 

在java中有没有办法做到这一点?

谢谢!

4 个答案:

答案 0 :(得分:2)

有几种方法可以让它更接近,但没有那么方便。

示例1:

SELECT * 
INTO #tmp_Dates
FROM [fn_Get_ates](@Date)

更新示例:

Map<String, Object> user = new HashMap<String, Object>() {
            {
                put("firstname", "myname");
                put("lastname", "surname");
                put("phone", new HashMap<String, String>() {
                    {
                        put("home", "123213213213");
                        put("office", "312321321312312");
                        put("mobile", "4532134213131312");
                    }
                });
            }
        };

添加另一张地图:

((Map)user.get("phone")).put("mobile2", "123");

(或许可以通过使用putIfAbsent方法或合并方法来改进)

打印当前内容:

user.put("address", new HashMap<String, Object>());

给出:

System.out.println(user);

答案 1 :(得分:1)

您可以使用Java中的JSON API以您喜欢的格式创建对象。以下是JSON API的文档

http://www.oracle.com/technetwork/articles/java/json-1973242.html

示例:

String stringToParse = "{" + 
    "firstname: \"myname\"," +
    "lastname: \"surname\"," +
    "phone: [ " + 
        " { home: \"123213213213\" }, " +
        " { office: \"312321321312312\" }," +
        " { mobile: \"4532134213131312\" }" +
    "]" +
"}";

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);

答案 2 :(得分:1)

例如,您可以使用以下代码:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- bean definitions here -->

</beans>

答案 3 :(得分:0)

可能&#34;可能&#34;但我认为这不是一个好习惯(除非我不知道另一种方式)。我相信这会奏效:

use std::ops::Add;
use std::borrow::Borrow;

#[derive(Clone, Debug)]
struct Point {
    x: i32,
    y: i32,
}

impl<T: Borrow<Point>> Add<T> for Point {
    type Output = Point;
    fn add(self, other: T) -> Point {
        Point { x: self.x + other.borrow().x, y: self.y + other.borrow().y }
    }
}

fn main() {
    let p1 = Point { x: 1, y: 0 };
    let p2 = Point { x: 2, y: 3 };
    let p4 = p1.clone() + &p2;
    let p3 = p1 + p2;
    println!("{:?}", p3);
    println!("{:?}", p4);
}

我认为你必须使用List对象类型而不是HashMap的数组数据类型。如果我这样做,我可能会创建自己的类来处理这种情况。