0

I want to convert this Json String to an Array. My hashmap named "HASHMRM" this is my Json String:

[
    {"id":1,"name":"hamid"},
    {"id":2,"name":"mohamad"},
    {"id":3,"name":"ali"},
    {"id":4,"name":"john"},
    {"id":5,"name":"smith"}
]

and I wanna to convert this Json String To an Array like this

String myJsonstring ="[{"id":1,"name":"hamid"},{"id":2,"name":"mohamad"},{"id":3,"name":"ali"},{"id":4,"name":"john"},{"id":5,"name":"smith"}]";
string[] AA = Jsons.....

int i =0;
while(i<string.lenght)
{
    HASHMRM.put(AA[i].split()//First, AA[i].split()//second);
    i++;
}

1 Answer 1

1

Use Gson.

First, you need POJO class that matches your data.

class MyUser {
    int id;
    String name;
}


Then, convert your string to List of POJO class.

// This is your string.
String myJsonString = "[{\"id\":1,\"name\":\"hamid\"},{\"id\":2,\"name\":\"mohamad\"},{\"id\":3,\"name\":\"ali\"},{\"id\":4,\"name\":\"john\"},{\"id\":5,\"name\":\"smith\"}]";

// Create new Gson object.
Gson gson = new Gson();

// Convert
List<MyUser> userList = gson.fromJson(myJsonString, new TypeToken<List<MyUser>>() {
    }.getType());


Next, use it!

for (MyUser u : userList) {
    HASHMRM.put(u.id, u.name);
} 

Remember: Instead of using the HASHMRM as variable name, I suggest you to use java conventional camel case name HashMRM.

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

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.