0

I have JSON as such:

{
  "Temperature": {
    "Name": "Temperature",
    "Value": "26.19",
    "Unit": "C"
  },
  "Humidity": {
    "Name": "Humidity",
    "Value": "29.38%",
    "Unit": "%"
  }
}

and I want to save it into List of objects of same type. Here is my class:

public class Measurement {
    private String name;
    private String value;
    private String unit;

    public Measurement(String name, String value, String unit){
        this.name = name;
        this.value = value;
        this.unit = unit;
    }

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }

    public String getUnit() {
        return unit;
    }

    @Override
    public String toString(){
        return name + " = " + value + unit;
    }
}

I have tried it usng gson like this:

Type measurementListType = new TypeToken<ArrayList<Measurement>>(){}.getType();

List<Measurement> msm = new Gson().fromJson(json, measurementListType);

but that gives error

Expected BEGIN_ARRAY but was BEGIN_OBJECT

Provided JSON is just an example, it could have any number of objects, but they would all have to follow same structure. How can I parse them into List? Any help is greatly appreciated.

1 Answer 1

1

For that JSON you're showing to be an array of objects, it needs to be sorrounded by square brackets, like this:

[{
    "Temperature": {
        "Name": "Temperature",
        "Value": "26.19",
        "Unit": "C"
    },
    "Humidity": {
        "Name": "Humidity",
        "Value": "29.38%",
        "Unit": "%"
    }
}]

From there you can have one or multiple objects inside the array.

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

1 Comment

So I changed JSON format to [ { "Name": "Temperature", "Value": "26.19", "Unit": "C" }, { "Name": "Humidity", "Value": "29.38%", "Unit": "%" } ] and it worked. I will accept your answer as it helped me understand what was wrong. Thank you.

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.