REST API和JSON解析

3

我正在使用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


请添加您收到的堆栈跟踪信息。 - WeMakeSoftware
6个回答

2
据我所知,您正在获取JSON数据,但想将其转换为自己的格式。这时您需要考虑使用类似于org.json的JSON库。
将字符串转换为JSONObject非常简单:
JSONObject obj = new JSONObject(output);

Maven 依赖:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20141113</version>
</dependency>

我建议您使用类似于http://unirest.io/java.html的工具来进行HTTP请求。请点击链接查看,非常容易上手。

1
org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) parser.parse(str); 

在你的代码上面一行中,你将str传递给了parser.parse(str),但它在你的类中没有定义。

0
你可以在webservice中实现它。Webservice必须返回结果。

MSISDN 123 SUBSCRIBERID 123

或者你可以解析json并获取你想要的结果,例如易于解析器。
 List<POJO> result = new ArrayList<>();
    url = new URL();
    InputStream is = url.openStream(url);
    JsonParser parser = Json.createParser(is);

    while (parser.hasNext()) {
        Event e = parser.next();
        if (e == Event.KEY_NAME) {
            switch (parser.getString()) {

                 case "KEY":
                    parser.next();
                    b.setKEY_MSISDN(parser.getString());
                    result.add(b);
                    break;
                 case "KEY":
                    parser.next();
                    b.setKEY_SUBSCRIBERID(parser.getString());
                    result.add(b);
                    b = new POJO();
                    break;

                default:
            }
        }
    }
    return result;

0
你可以尝试类似以下的代码:
public class MyMessage {
    private int errorCode;
    private String errorMessage;
    private KeyParamArray myParams;
    /*
    add getters and setters
    */
}

public class KeyParam {
    private Entry[] entries;
    /*
    add getter and setter
    */
}

public class Entry {
    private String key;
    private String value;
    /*
    add getters and setters
    */
}

@Path("rest")
public class RestServices {

    @POST
    @Consumes("application/json")
    public Response saveMyMessage(MyMessage message) {
        // do what you want with the message
        return Response.ok();
    }
}

你可以使用Jersey来创建REST服务,使用Jackson作为JSON解析器。 Maven依赖如下:

            <dependency>
                <groupId>com.sun.jersey</groupId>
                <artifactId>jersey-core</artifactId>
                <version>1.9.1</version>
            </dependency>
            <dependency>
                <groupId>com.sun.jersey</groupId>
                <artifactId>jersey-server</artifactId>
                <version>1.9.1</version>
            </dependency>
            <dependency>
                <groupId>com.sun.jersey</groupId>
                <artifactId>jersey-bundle</artifactId>
                <version>1.9.1</version>
            </dependency>
            <dependency>
                <groupId>com.sun.jersey</groupId>
                <artifactId>jersey-json</artifactId>
                <version>1.9.1</version>
            </dependency>

            <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-jaxrs</artifactId>
                <version>1.8.3</version>
                <scope>provided</scope>
            </dependency>

你可以使用更新版本的库,这些只是我正在开发项目中使用的。


0
String jsonString = "{\"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\"}]}}";
    org.codehaus.jettison.json.JSONObject json;
    try {
        json = new org.codehaus.jettison.json.JSONObject(jsonString.toString());

    org.codehaus.jettison.json.JSONObject responseData = json.getJSONObject("keyParamArray");
    final JSONArray geodata = responseData.getJSONArray("KeyParam");
    final int n = geodata.length();
    for (int i = 0; i < n; ++i) {
      final org.codehaus.jettison.json.JSONObject person = geodata.getJSONObject(i);

     System.out.println(person.getString("key"));
    }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }

-1

这个解决方案是使用 JavaScript 编写的,通过将 XML 解析为 JSON 并对我很有效。

 var resultjson = JSON.stringify(result, null, 2);
 var js = JSON.parse(resultjson);
 var msisdnvar = js.abcReturn.keyParam.keyParam[0].key.$value;
 var msisdnval = js.abcReturn.keyParam.keyParam[0].value.$value;
 var subscribervar = js.abcReturn.keyParam.keyParam[1].key.$value;
 var subscriberval = js.abcReturn.keyParam.keyParam[1].value.$value;
 console.log(msisdnvar+': '+msisdnval+', '+subscribervar+': '+subscriberval);

将会输出如下结果:

MSISDN: 123,SUBSCRIBERID: 123

注意:请将abcReturn更改为您的API名称,例如"API-NameReturn"


享受吧 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接