3

I'm writing code in Java for REST and the output which I'm getting is in JSON format. I want to parse the JSON string into a simple string in Java but I'm 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();
        }



    } 

}         

the output is

{
    "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 output as

MSISDN 123
 SUBSCRIBERID 123

... and so on

1
  • please add the stacktrace you're getting. Commented May 8, 2015 at 7:06

6 Answers 6

2

As far as i understand, youre getting json, but want to turn it into your own format. The you should consider using a json library like org.json.

Turning the string into 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 would also suggest to use something like http://unirest.io/java.html for the http request, follow the link, its really easy.

Sign up to request clarification or add additional context in comments.

Comments

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

in above line of your code, you have passed str to parser.parse(str) but it's defined nowhere in your class .

Comments

0

You can do it in webservice. Webservice must return result this.

MSISDN 123 SUBSCRIBERID 123

Or you can parse json and get what you want. for example easy 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;

Comments

0

You can try with 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 for rest services and Jackson as the Json parser. Maven dependencies are the following :

            <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 could use newer versions of the libraries, these are just the one I use in a project I'm working on).

Comments

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

Comments

-1

This solution is in java Script by using parsing from xml to JSON and work fine 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 give output as;

MSISDN: 123, SUBSCRIBERID: 123

Note: Please change abcReturn with your API-Name like "API-NameReturn"


Enjoy :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.