P15GEN2\59518
2024-05-29 d4210c7c4b04abde20037ea8aa0f54ef8a2649aa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package foundation.icall.callout;
 
import java.util.ArrayList;
import java.util.List;
 
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
 
import foundation.dao.bizlogic.IJSONResponse;
import foundation.json.JArrayReader;
import foundation.json.JObjectReader;
import foundation.json.JSONReader;
import foundation.json.JType;
import okhttp3.Response;
import okhttp3.ResponseBody;
 
public class JSONResponse implements IJSONResponse {
    
    protected static Logger logger;
    private JSONReader reader;
    private List<String> errors;
    private String content;
    private int resultCode;
 
    static {
        logger = LogManager.getLogger(JSONResponse.class);
    }
    
    public JSONResponse(Response response) {
        errors = new ArrayList<String>();
        
        if (response == null) {
            errors.add("调用没有返回");
            return;
        }
 
        resultCode = response.code();
        
        if (!response.isSuccessful()) {
            errors.add("错误码: " + response.code());
        }
        
        try {
            ResponseBody body = response.body();
            content = body.string();
            
            JType type = JSONReader.readType(content);
            
            if (JType.Object == type) {
                reader = new JObjectReader(content);
            }
            else if (JType.Array == type) {
                reader = new JArrayReader(content);
            }
            else {
                logger.error("invalid json for JSONResponse");
                reader = null;
            }
        }
        catch (Exception e) {
            errors.add(e.getMessage());
            e.printStackTrace();
        }
    }
 
    public String getString(String name) {
        if (reader == null) {
            return null;
        }
        
        return reader.getRawString(name); 
    }
    
    public JArrayReader parseJArrayReader() {
        if (reader == null) {
            return null;
        }
        
        return (JArrayReader) reader; 
    }
 
    public boolean hasErrors() {
        return !errors.isEmpty();
    }
 
    public int getResultCode() {
        return resultCode;
    }
 
    @Override
    public String toString() {
        return content;
    }
    
}