0

I have a JSON Object in The Form

{"pageId":1,"stgId":1,"userId":2,"requestStageId":0,"requestPageId":0,"answer":[{"qId":"6","ansValue":"1"},{"qId":"11","ansValue":"10"}]}

I receive the data as :

long uid = (long)inputJsonObj.get("userId");
long stgid = (long)inputJsonObj.get("stgId");
long pgid = (long)inputJsonObj.get("pageId");
JSONArray answer_Array =    (JSONArray) inputJsonObj.get("answer");

ie, answer_Array conatins :

[{"qId":"6","ansValue":"1"},{"qId":"11","ansValue":"10"}]

Now I need To Convert the JSONArray answer_Array To LinkedHashMap, where qid will be the key and ansValue will be the Value.

How can This be done ?

5
  • This won't give you the expected datastructure for free, but you'll be able to build it yourself: stackoverflow.com/questions/2591098/how-to-parse-json-in-java Commented Dec 5, 2014 at 9:38
  • check this stackoverflow.com/a/17037364/1939607 Commented Dec 5, 2014 at 9:40
  • 1
    Are you using Jackson or any json lib for parsing json? Commented Dec 5, 2014 at 9:44
  • @iNan : I am using org.json.simple.parser.JSONParser Commented Dec 5, 2014 at 9:50
  • if you ll use Hashmap then problem ll be there because, there can be multiple record whose key name is qId, so when we add in Hashmap it will overwrite the existing one whose key value in qId. Commented Dec 5, 2014 at 10:04

4 Answers 4

1

You can iterate the Array and use this method

public static Map parseStringToMap(String param)
    {
        Map result  =   new HashMap<String,String>();
        if(param!=null)
        {
            StringBuffer sb     =   new StringBuffer(param);    
            try
            {
                String str  =   sb.substring(1, sb.length()-1);
                String[] srArray    =   str.split(",");
                String tempStr  =   null;
                for(int i=0;srArray!=null && i<srArray.length;i++)
                {
                    tempStr =   srArray[i];
                    if(tempStr!=null && tempStr.contains(":"))
                    {
                        String[] keyVal =   tempStr.split(":");
                        if(keyVal.length>1)
                            result.put(keyVal[0], keyVal[1]);
                        else
                            result.put(keyVal[0], "");
                    }

                }

            }
            catch(Exception e)
            {
                System.out.println("In JSONConverter: Issue while parsing the JSON => "+e.getMessage());
                e.printStackTrace();
            }
        }
        return result;  
    }
Sign up to request clarification or add additional context in comments.

Comments

1

You can write a helper method which takes answer array as input and returns map of question and answer.

private static Map<String, String> getHashMapFromJson(JSONArray answer_Array) {

        Map<String, String> qaMap = new LinkedHashMap<String, String>();

        Iterator<JSONObject> iterator = answer_Array.iterator();

        while (iterator.hasNext()) {
            JSONObject value = iterator.next();

            qaMap.put((String) value.get("qId"), (String) value.get("ansValue"));
        }

        return qaMap;
    }

Comments

1

You Can do something like (To Avoid Overwrite):

Map result  =   new HashMap<String,String>();
for( int i = 0 ; i < jArray.length() ; i++ ){
       JSONObject object = jArray.getJSONObject(i);
       result.put(object.getString("qId"), object.getString("ansValue"));
}

for (Object variableName: result.keySet()){
       System.out.println(String.valueOf(variableName));
       System.out.println(result.get(variableName));
}

Main Reason I have done "qId"+i is that you want data in Hashmap so if the same key then it ll overwrite the already exist. and you want qId as key.

It's better to use List instead of it and make one class of data it will work perfect.

OR YOU CAN TRY

My code (With List):

static class KeyVal{
    String qkey; String qval; String akey; String aval;
    public String getQkey() {return qkey;}
    public void setQkey(String qkey) { this.qkey = qkey;}
    public String getQval() {return qval;}
    public void setQval(String qval) {this.qval = qval;}
    public String getAkey() {return akey;}
    public void setAkey(String akey) {this.akey = akey;}
    public String getAval() {return aval;}
    public void setAval(String aval) {this.aval = aval;}
}
List<KeyVal> data = new ArrayList<>();
KeyVal key;
for( int i = 0 ; i < ja.length() ; i++ ){
    JSONObject object = ja.getJSONObject(i);
    key = new KeyVal();
    key.setQkey("qId"); key.setQval(object.getString("qId"));
    key.setAkey("ansValue"); key.setAval(object.getString("ansValue"));
    data.add(key);
}
for( int i = 0 ; i < data.size() ; i++ ){
    System.out.println(data.get(i).getQkey() + " : " + data.get(i).getQval());
    System.out.println(data.get(i).getAkey() + " : " + data.get(i).getAval());
}

Comments

0

This method Works For me ->

 /* Extract The JSONArray and insert The qid and ansValue into the HashMap<String,String> */

       JSONArray answer =    (JSONArray) inputJsonObj.get("answer");                                   
               JSONParser parser3 = new JSONParser();
               JSONObject jsonObject3 = null;
               for(int i=0;i< answer.size();i++){                      
                    System.out.println(answer.get(i).toString());
                    Object obj3 = parser3.parse(answer.get(i).toString());
                    jsonObject3 = (JSONObject) obj3;
                    String qid = (String) jsonObject3.get("qId");
                    String ansValue = (String) jsonObject3.get("ansValue");                     
                    map.put(qid, ansValue);
               }

1 Comment

What is the size of map ? Is it overwrite ? can you print map data ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.