REST api and json parsing

I am writing code in Java for REST and the output I get is in JSON format. I want to parse a JSON string into a simple string in Java, but I am getting errors. Below is my code:

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();
        }



    } 

}         

      

output

{
    "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"
            }
        ]
    }
}

      

So, I want the result to be

MSISDN 123
 SUBSCRIBERID 123

      

... etc.

+3


source to share


6 answers


As I understand it, you are receiving json, but you want to turn it into your own format. You should use a json library like org.json.

Including a string in a JSONObject is as easy as:

JSONObject obj = new JSONObject(output);

      



Maven dependency:

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

      

I also suggest using something like http://unirest.io/java.html for the http request, following the link it is very simple.

+2


source


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

      



at the top line of your code, you've gone str

before parser.parse(str)

, but it isn't listed anywhere in your class.

+1


source


You can do this in webservice. The webservice should return a result.

MSISDN 123 SUBSCRIBERID 123

Or you can parse the json and get what you want. for example a simple parser

 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


source


You can try something similar to this:

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();
    }
}

      

And you can use Jersey to serve rest and Jackson as a Json parser. Maven dependencies are as follows:

            <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>

      

(You can use newer versions of the libraries, this is just the one I am using in the project I am working on).

0


source


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();
    }
    }

      

0


source


This solution is in java Script using parsing from xml to JSON and works great for me.

 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);

      

Will output as:

MSISDN: 123, SUBSCRIBERID: 123

Note. Please change abcReturn with your API name like "API-NameReturn"


Enjoy :)

-1


source







All Articles