java使用json将HashMap转化成javabean小例子

时间:2022-06-15 19:08:03

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import net.sf.json.JSONObject;

/**  * 使用json将HashMap转化成javabean.

 * @author Administrator

 * @Date   2015-7-18  */

public class People {

private String nameString;

private String ageString;

public String toString(){

   return "[nameString="+nameString+"########"+"ageString="+ageString+"]";

  }

public String getNameString() {  return nameString; } public void setNameString(String nameString) {  this.nameString = nameString; } public String getAgeString() {  return ageString; } public void setAgeString(String ageString) {  this.ageString = ageString; }

public static void main(String[] args) {  Map<String, String> map2 = new HashMap<String,String>();  String []strings = {"nameString","ageString"};  Map<String, String> map = new HashMap<String, String>();  map.put("nameString", "zhangsan");  map.put("ageString", "89");  map.put("sexString", "male");  Iterator<String> it = map.keySet().iterator();  while(it.hasNext()){      String keyString = it.next();   String valueString = map.get(keyString);   for(String s :strings){    if(s==keyString){          map2.put(keyString,valueString);              }    continue;       }           }  JSONObject jsonObject = JSONObject.fromObject(map2);  People people = (People)JSONObject.toBean(jsonObject, People.class);  System.out.println(people.toString()); } }