0

I have a HashMap like so

Map<String , String>

when I get an element from the map by key it returns

["6"] I need only the 6 , not ["6"]

The value is added like so

map.put(k , jsonarray.toString()) ; 

Thanks

6
  • also the value could contain many ["2" , "4" , "1"] ect Commented Mar 26, 2017 at 17:08
  • Could you also post jsonarray.toString() sample ? Commented Mar 26, 2017 at 17:11
  • What is expected output in case the value for a certain key is ["2", "4", "1"]? Commented Mar 26, 2017 at 17:15
  • the 2 , 4 ,1 are dataset id's these datasets names would be placed in a list and returned to the caller Commented Mar 26, 2017 at 17:45
  • @YarpoleCosgrave consider commenting to posted answers to know whether your problem was resolved or not. Commented Mar 27, 2017 at 2:46

4 Answers 4

1

Then you have 2 options change your map to

Map<String,Integer>

and then you'll need to put an int value inside

or when getting the value use:

Integer.valueOf(map.get("key"));

thats only valid in case your String inside the json is only an int - our you will get an exception!

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

3 Comments

I feel chaning the map would be best.
is it possible to put a json array there as in Interger ?
Youll have to parse it first before u put it inside the map
0

You can use Integer#parseInt(String) to convert a String to an Integer

int value = Integer.parseInt(map.get("key"));

1 Comment

This approach does not work.Unless you parse the string first. on first pass the [ is evaluated and returns an error as [ in not an integer , same for " .. as highlighted by @J. N
0

You get only what you actually put in as value in the Map. So instead of using toString() while storing, you could put in the just the value which is 6 and for the multiple values you could put in an array of integer values.

Comments

0

Change your Map to String and JsonArray and store JsonArray directly instead of converting it to String

 Map<String , JsonArray>

Using your Map key, iterate your JsonArray object

JsonArray jsonArray;
Iterator<JsonElement> it = jsonArray.iterator();
while(it.hasNext()){
    System.out.println(it.next());
}

1 Comment

I think in most cases this would be the one of the best answers, But for my use case it moves json parsing from the parsing layer to the transport layer

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.