CXF,RESTEASY返回格式为JSON时,如果类型为String的值为数值时,JSON中引号消失的问题解决

在使用CXF或RESTEASY等框架构建REST方式的WEB SERVICE的应用时候

如:
使用JAXB注解定义一个返回的对象
@XmlRootElement(name = "user")
@XmlType(propOrder = { "id", "nickName", "signature", "birthday", "gender" })
@XmlAccessorType(XmlAccessType.FIELD)
public class GetResponse {
		private Long id;
		private String nickName;
...


当返回格式为JSON的时候,如果nickName的值是12345,则返回的JSON内容为:

{"id":1,"nickName":12345}


按理说json的内容应该为:
{"id":1,"nickName":"12345"}

12345应该有引号。




要解决这个问题,需要修改相关的底层代码:


//修改com.sun.xml.bind.v2.runtime.XMLSerializer.java 


public void leafElement(Name tagName, String data, String fieldName) throws SAXException, IOException, XMLStreamException {
		Object currentObj = cycleDetectionStack.peek();
		if (out instanceof com.sun.xml.bind.v2.runtime.output.XMLStreamWriterOutput) {  //判断out的类型,XMLStreamWriterOutput为json或其他非xml格式的writer 
			Field field = null;
			try {
				field = currentObj.getClass().getDeclaredField(fieldName);
			} catch (Exception e1) {
				try {
					field = currentObj.getClass().getField(fieldName);
				} catch (Exception e2) {

				}      取的当前字段的类型信息
			}
			if (field != null && field.getType().getName().equals("java.lang.String")) { //如果为字符串并且字符串为数字格式,增加标记 $:
				if (isNumber(data)) {
					data = "$:" + data;
				}
			}
		}
....

//修改org.codehaus.jettison.mapped.DefaultConverter.java或自己定义一个实现

public Object convertToJSONPrimitive(String text) {
		if (text == null)
			return text;
		Object primitive = null;

		// Attempt to convert to Integer 
//----------------------------数值类型字符串不能正确转换的元凶在这里 
		try {
			primitive = ENFORCE_32BIT_INTEGER ? Integer.valueOf(text) : Long.valueOf(text);
		} catch (Exception e) {/**/
		}
		// Attempt to convert to double
		if (primitive == null) {
			try {
				Double v = Double.valueOf(text);
				if (!v.isInfinite() && !v.isNaN()) {
					primitive = v;
				} else {
					primitive = text;
				}
			} catch (Exception e) {/**/
			}
		}
		// Attempt to convert to boolean
		if (primitive == null) {
			if (text.trim().equalsIgnoreCase("true") || text.trim().equalsIgnoreCase("false")) {
				primitive = Boolean.valueOf(text);
			}
		}

		if (primitive == null || !primitive.toString().equals(text)) {
			// Default String
			if (text.startsWith("$:")) {          //如果字符串含有标记,去掉标记
				text = text.substring(2);
			}

			primitive = text;
		}

		return primitive;
	}

你可能感兴趣的:(java,json,xml,REST,sun)