欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Google Gson - 将给定的Json转换为Map中嵌套Map的数据结构

程序员文章站 2022-07-12 12:15:52
...

一、Json如下

 

{
    "lbmember_hash": {
        "10.2.180.74:1300": {
            "protocol": "ANY",
            "opsState": "up",
            "ip": "10.2.180.74",
            "server": "10.2.180.74",
            "port": "1300"
        },
        "10.2.181.160": {
            "protocol": "ANY",
            "opsState": "up",
            "ip": "10.2.181.160",
            "server": "10.2.181.160",
            "port": "1119"
        }
    }
}

 

 

二、定义对应的Java Bean

 

/**
 * 
 */
package com.ebay.tools.cms.sync.model.lb;

/**
 * 
 * LBMember ResourceId: ip:port
 * 
 * @author Josh Wang(Sheng)
 * 
 * @email  swang6@ebay.com
 * 
 */
public class LBMemberSource extends LBSource {

	private static final long serialVersionUID = -3579858609342297799L;
	
	private String memberName; // ip:port - resource id

	private String ip;
	
	private String opsState;
	
	private int port;
	
	private String protocol;
	
	private String server;
	
	private String label;

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public String getOpsState() {
		return opsState;
	}

	public void setOpsState(String opsState) {
		this.opsState = opsState;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getProtocol() {
		return protocol;
	}

	public void setProtocol(String protocol) {
		this.protocol = protocol;
	}

	public String getServer() {
		return server;
	}

	public void setServer(String server) {
		this.server = server;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public String getMemberName() {
		return memberName;
	}

	public void setMemberName(String memberName) {
		this.memberName = memberName;
	}

	@Override
	public String toString() {
		return "LBMemberSource [memberName=" + memberName + ", ip=" + ip + ", opsState=" + opsState + ", port=" + port + ", protocol=" + protocol
				+ ", server=" + server + ", label=" + label + "]";
	}
	
	
	
}

 

三、给出具体的转换类

/**
 * 
 */
package com.ebay.tools.cms.sync.utils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;

import com.ebay.tools.cms.sync.model.SyncSource;
import com.ebay.tools.cms.sync.model.lb.LBMemberSource;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

/**
 * @author Josh Wang(Sheng)
 * 
 * @email  swang6@ebay.com
 * 
 */
public class GsonConverter<T extends SyncSource> {
	
	private Type genericType;
	
	public GsonConverter() {
		Type typeClass = getClass().getGenericSuperclass();
		genericType = ((ParameterizedType) typeClass).getActualTypeArguments()[0];
	}
	
	public static Map<String, String> json2Map(String jsonString) {
		Type type = new TypeToken<Map<String, String>>() {
			private static final long serialVersionUID = 1L;}.getType();
		Gson gson = new Gson();
		return gson.fromJson(jsonString, type);
	}
	
	public  Map<String, Map<String, LBMemberSource>> json2Maps(String jsonString) {
		Type typeToken = buildTypeToken(genericType);
		
		Gson gson = new Gson();
		return gson.fromJson(jsonString, typeToken);
	}
	
	private Type buildTypeToken(Type genericType) {
		Type typeToken = null;
		if (genericType.toString().endsWith(LBMemberSource.class.getSimpleName())) {
			typeToken = new TypeToken<Map<String, Map<String, LBMemberSource>>>() {
				private static final long serialVersionUID = 1L;}.getType();
		}
		
		return typeToken;
	}
	
}

 

 

 

 

四、为便于测试,写一个IOUtils来读取上面的json文本,从而避免在测试用例中麻烦的输入Json文本

/**
 * 
 */
package com.ebay.tools.cms.sync.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;



/**
 * @author Josh Wang(Sheng)
 * 
 * @email  swang6@ebay.com
 * 
 */
public class IOUtils {

	public static String fileToString(String filePath) throws IOException {
		File file = new File(filePath);
		
		InputStream in = new FileInputStream(file);
		try {
			return org.apache.commons.io.IOUtils.toString(in);
		} finally {
			org.apache.commons.io.IOUtils.closeQuietly(in);
		}
	}

}

 

五、最后给出测试类

/**
 * 
 */
package com.ebay.tools.cms.sync.util;


import java.io.IOException;



import java.util.Map;

import org.junit.Assert;
import org.junit.Test;

import com.ebay.tools.cms.sync.BaseTest;
import com.ebay.tools.cms.sync.model.lb.LBMemberSource;
import com.ebay.tools.cms.sync.utils.GsonConverter;
import com.ebay.tools.cms.sync.utils.IOUtils;

/**
 * @author Josh Wang(Sheng)
 * 
 * @email  swang6@ebay.com
 * 
 */
public class TestGsonConverter extends BaseTest {
	

	@Test
	public void json2Map() throws IOException {
		String lbmemberHashPath = "src/test/resources/lbmember_hash.txt";
		String hashString = IOUtils.fileToString(lbmemberHashPath);
		Assert.assertNotNull(hashString);
		
		Map<String, Map<String, LBMemberSource>> map = new GsonConverter<LBMemberSource>(){}.json2Maps(hashString);
		for (Map.Entry<String, Map<String, LBMemberSource>> entry : map.entrySet()) {
			printHighlight(entry.getKey());
			for (Map.Entry<String, LBMemberSource> entry2 : entry.getValue().entrySet()) {
				print(entry2.getValue().toString());
			}
		}
	}
	
}

 

 本例中使用了Google Json中的TypeToken来获取具体泛型类的泛型参数类型,有关获取Java中泛型类的泛型参数类型,可参见另一篇博客:http://josh-persistence.iteye.com/blog/2165613