Java 프로젝트에서 WebSocket을 사용하여 구독을 얻었으며 소켓에서 다음과 같은 다양한 응답을 얻습니다 JSONArray
.
[
68,
"te",
[
80588348,
1508768162000,
0.01569882,
5700.8
]
]
JAVA
이 응답에 대해 어떻게 반대 해야 합니까? 이 개체로 어떻게 변환 할 수 있습니까?
[
68, <- Integer
"te", <- String
[
80588348, <- Long
1508768162000, <- Long
0.01569882, <- Double
5700.8 <- Double
]
]
다음과 같은 다른 응답이 있다는 한 가지 문제가 있습니다.
{"event":"subscribed","channel":"trades","chanId":68,"symbol":"tBTCUSD","pair":"BTCUSD"}
그리고 난으로 변환하려고 할 때 new JSONArray(response)
이 발생합니다org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1].
이 필드를 가져오고 변환하는 방법 (첫 번째 응답 예제)?
나는 다음과 같은 것을 얻고 싶다.
public class Details{
public Long id;
public Long timestamp;
public Double amount;
public Double price;
}
public class Response{
public Integer id;
public String type;
public Details details;
}
요청 된 파서 클래스 :
public class JsonParser {
public static Response toJavaObject(String str) {
String[] fields = str.split(",");
Response res = new Response();
res.setId(Integer.valueOf(fields[0].substring(1)));
res.setType(fields[1].replaceAll("\"", ""));
Details dtl = new Details();
dtl.setId(Long.valueOf(fields[2].substring(1)));
dtl.setTimestamp(Long.valueOf(fields[3]));
dtl.setAmount(Double.valueOf(fields[4]));
dtl.setPrice(Double.valueOf(fields[5].substring(0, fields[5].length() - 2)));
res.setDetails(dtl);
return res;
}
}
class Details {
public Long id;
public Long timestamp;
public Double amount;
public Double price;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
class Response {
public Integer id;
public String type;
public Details details;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Details getDetails() {
return details;
}
public void setDetails(Details details) {
this.details = details;
}
}
이 JsonParser를 사용하려면
예를 들어 지금 코드에서 :
public static void main(String args[]) {
String str = "[68,\"te\",[80588348,1508768162000,0.01569882,5700.8]]";
Response res = JsonParser.toJavaObject(str);
// your logic below...
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다