使用hashmap替换名称

时间:2015-12-11 07:30:36

标签: java json hashmap

My java class

    public class Mainclass {

    public static void main(String[] agrs) {

    BeanClass beanclass1 = new BeanClass();
    BeanClass beanclass2 = new BeanClass();
    BeanClass beanclass3 = new BeanClass();
    BeanClass beanclass4 = new BeanClass();
    BeanClass beanclass5 = new BeanClass();

    beanclass1.setId(1);
    beanclass1.setName("Peter");
    beanclass1.setAddress("WI");

    beanclass2.setId(2);
    beanclass2.setName("Jack");
    beanclass2.setAddress("Aus");

    beanclass3.setId(3);
    beanclass3.setName("Vivek");
    beanclass3.setAddress("canada");

    beanclass4.setId(4);
    beanclass4.setName("Deva");
    beanclass4.setAddress("Calf");

    beanclass5.setId(5);
    beanclass5.setName("Arun");
    beanclass5.setAddress("NY");

    Gson gson = new Gson();
    HashMap<String,BeanClass> hm1 = new HashMap<>();
    hm1.put("First", beanclass1);
    hm1.put("Second", beanclass2);
    hm1.put("Third", beanclass3);
    hm1.put("Fourth", beanclass4);
    hm1.put("Fifth", beanclass5);
    String st = gson.toJson(hm1);
    System.out.println(st);
    HashMap hm = gson.fromJson(st, HashMap.class);
    System.out.println(hm);
  //  HashMap hm = gson.fromJson(st, HashMap.class);
   // System.out.println(hm); here to change beanclass3 name..
    }}
    output:{"Second":{"id":2,"name":"Jack","address":"Aus"},"Third": {"id":3,"name":"Vivek","address":"Canada"},"First":{"id":1,"name":"peter","address":"WI"},"Fourth":{"id":4,"name":"Deva","address":"calf"},"Fifth":{"id":5,"name":"Arun","address":"NY"}}
  

{Second = {id = 2.0,name = Jack,address = Orrisa},Third = {id = 3.0,   name = Vivek,address = Kerala},First = {id = 1.0,name = Ram,   address = Chennai},Fourth = {id = 4.0,name = Deva,address = WestBengal},   Fifth = {id = 5.0,name = Arun,address = Mumbai}}

这里我需要更改第三个beanclass3名称来改变......怎么办?

1 个答案:

答案 0 :(得分:0)

如果您询问如何更新beanclass3中存储的HashMap名称:

((BeanClass)(hm.get("Third"))).setName("newName");