我正在使用Java编写REST的代码,输出格式为JSON。我想将JSON字符串解析为简单字符串,但一直出现错误。以下是我的代码:
package restapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.Iterator;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class testapp {
public static void main(String[] args) throws JSONException, ParseException {
String output = "abc";
try {
URL url = new URL("http://ip/sss-wsrcrest-controller-5.2.3.1/wsrcservice/wsrc/v1/processGet?subSystemId=external&subSystemPassword=password&operation=listSubscriptions&MSISDN=1111");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
//String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JSONParser parser = new JSONParser();
//System.out.println(str);
org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) parser.parse(str);
try {
org.json.simple.JSONArray msg = (org.json.simple.JSONArray) jsonObject.get("keyParamArray");
int n = (msg).length();
for (int i = 0; i < n; ++i) {
JSONObject person = (msg).getJSONObject(i);
System.out.println(person.getInt("key"));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
输出是:
{
"errorCode": "0",
"errorMessage": "processed successfully",
"keyParamArray": {
"KeyParam": [
{
"key": "MSISDN",
"value": "123"
},
{
"key": "SUBSCRIBERID",
"value": "123"
},
{
"key": "CUSTOMNUMFIELD9",
"value": "0"
},
{
"key": "CUSTOMNUMFIELD10",
"value": "0"
},
{
"key": "CUSTOMNUMFIELD6",
"value": "0"
},
{
"key": "CUSTOMNUMFIELD5",
"value": "0"
},
{
"key": "CUSTOMNUMFIELD8",
"value": "0"
},
{
"key": "CUSTOMNUMFIELD7",
"value": "0"
},
{
"key": "CUSTOMNUMFIELD2",
"value": "0"
},
{
"key": "CUSTOMNUMFIELD1",
"value": "0"
},
{
"key": "CUSTOMNUMFIELD4",
"value": "0"
},
{
"key": "CUSTOMNUMFIELD3",
"value": "0"
},
{
"key": "PARENTSUBSCRIBERID",
"value": "0"
},
{
"key": "ACTIVE",
"value": "1"
},
{
"key": "BARRINGSTATUS",
"value": "1"
}
]
}
}
所以我希望您将输出作为
MSISDN 123
SUBSCRIBERID 123
... and so on