1

I'm using PHP to return a JSON encoded associative array to a client. The array is constructed by looping through the result set of a MySQL database query. For simplicity's sake, instead of showing all the code that returns the result set, let's say that one possible output to the query produces the following associative array in PHP:

$ResultRows = array(
    "10 m" => 10,
    "100 m" => 100,
    "1000 m" => 1000
);

echo json_encode($ResultRows);

The JSON string produced by json_encode looks like this:

{"10 m":10,"100 m":100,"1000 m":1000}

As you can see, it gets encoded like an object with each key-value pair looking like a property name and value.

Now, the client running Java receives this JSON encoded string. I would like to create an instance of LinkedHashMap<String, Double> that is populated by these values. However, since it is not encoded like an array, I'm having a hard time seeing how to use GSON to decode this. Any ideas?

I could simply change the PHP and create a simple object that holds the Key/Value pairs and return a regular array of these objects, but I was hoping to leave the PHP scripts alone if possible because there are quite a few of them to change.

1 Answer 1

2

You can provide a type to the fromJson method with the TypeToken class, so it would be something like this:

public class Test {
    public static void main(String[] args) {
        String json ="{\"10 m\":10,\"100 m\":100,\"1000 m\":1000}";
        LinkedHashMap<String, Double> map = new Gson().fromJson(json, new TypeToken<LinkedHashMap<String, Double>>(){}.getType());
        System.out.println(map);
    }
}

Which output:

{10 m=10.0, 100 m=100.0, 1000 m=1000.0}
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly! Thanks! Btw, I like your quote from Linus in your profile.

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.