2016-07-13 2 views
2

몇 가지 String 변수가 포함 된 Java 객체가 있습니다. String 값 중 하나가 영숫자 인 경우 Java 객체에서 json 메시지를 만들 때 변환은 따옴표로 묶인 값을 반환합니다. 그렇지 않으면 변환이 숫자 값을 반환합니다.Java의 JSON 파서가 자동으로 문자열을 숫자/정수로 변환합니다.

예 : 다음 JSON 변환이 다시 (숫자)

"userid":"tom""password":123456을 반환

Class User { 
    String userid , password; 
} 

userid = "tom" 경우 password = "123456"

그것은 실제로 내가 달성 할 수있는 방법 "password":"123456"

를 반환해야 이? json.org의 Java 파서를 사용하고 있으며 아래에는 Java 객체를 Json으로 변환하는 코드 스 니펫이 있습니다.

final JSONObject jsonObject = XML.toJSONObject(writer.toString()); 
res = jsonObject.toString(4); 

답변

1

그것은 때문에 JSONObject에서 stringToValue 방법을합니다. 형식을 추측하려고 시도합니다. 오픈 소스이므로 원하는 경우 변경할 수 있습니다. 그냥 문자열을 반환합니다.

/** 
* Try to convert a string into a number, boolean, or null. If the string 
* can't be converted, return the string. 
* 
* @param string 
*   A String. 
* @return A simple JSON value. 
*/ 
public static Object stringToValue(String string) { 
    if (string.equals("")) { 
     return string; 
    } 
    if (string.equalsIgnoreCase("true")) { 
     return Boolean.TRUE; 
    } 
    if (string.equalsIgnoreCase("false")) { 
     return Boolean.FALSE; 
    } 
    if (string.equalsIgnoreCase("null")) { 
     return JSONObject.NULL; 
    } 

    /* 
    * If it might be a number, try converting it. If a number cannot be 
    * produced, then the value will just be a string. 
    */ 

    char initial = string.charAt(0); 
    if ((initial >= '0' && initial <= '9') || initial == '-') { 
     try { 
      if (string.indexOf('.') > -1 || string.indexOf('e') > -1 
        || string.indexOf('E') > -1 
        || "-0".equals(string)) { 
       Double d = Double.valueOf(string); 
       if (!d.isInfinite() && !d.isNaN()) { 
        return d; 
       } 
      } else { 
       Long myLong = new Long(string); 
       if (string.equals(myLong.toString())) { 
        if (myLong.longValue() == myLong.intValue()) { 
         return Integer.valueOf(myLong.intValue()); 
        } 
        return myLong; 
       } 
      } 
     } catch (Exception ignore) { 
     } 
    } 
    return string; 
} 
0

대신 staxon 라이브러리를 사용할 수 있습니다 JsonXMLConfigBuilder이 수의 경우 (예 : 당신은 당신이 원시 값을 처리하는 방법을 정의 할 수 있습니다 autoprimitive 등) 변환하는 동안 동작을 제어합니다. 여기 코드는 다음과 같습니다

String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><userid>tom</userid><password>123456</password></root>"; 
ByteArrayOutputStream bao = new ByteArrayOutputStream(); 
JsonXMLConfig config = new JsonXMLConfigBuilder().autoArray(true).autoPrimitive(false).prettyPrint(true).build(); 
try { 
    XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(IOUtils.toInputStream(xml)); 
    XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(bao); 

    writer.add(reader); 
    reader.close(); 
    writer.close(); 
} finally { 
    bao.close(); 
} 

String json = bao.toString(); 

JsonXMLConfigBuilder()...autoPrimitive(false) 당신이 찾고있는 트릭을 수행합니다 숫자 필드는 문자열로 유지됩니다. 이 코드 샘플로

, 당신은 추가 할 필요가 Saxion + 평민-IO (단지 IOUtils.toInputStream(xml)에 대한) : staxon에

<dependency> 
    <groupId>de.odysseus.staxon</groupId> 
    <artifactId>staxon</artifactId> 
    <version>1.3</version> 
</dependency> 

<dependency> 
    <groupId>commons-io</groupId> 
    <artifactId>commons-io</artifactId> 
    <version>2.4<version> 
</dependency> 

일부 문서 :

관련 문제