Разбор Json данных. Вложенные объекты выдают ошибку - PullRequest
1 голос
/ 14 июля 2020

Итак, у меня есть эти данные, как показано ниже, и я пытаюсь проанализировать данные, но я могу многое узнать о синтаксическом анализе JSONArrays в Интернете, но не столько об объектах внутри объектов. У меня был go, и я получаю сообщение об ошибке. Вот ответ Json. Я пытаюсь вернуть только отмеченные поля:

{
    "geomagnetic-field-model-result": {
        "model": "wmm",
        "model_revision": "2020",
        "date": {
            "value": "2020-07-14"
        },
        "coordinates": {
            "latitude": {
                "units": "deg (north)",
                "value": 0.0
            },
            "longitude": {
                "units": "deg (east)",
                "value": 0.0
            },
            "altitude": {
                "units": "km",
                "value": 0.00
            }
        },
        "field-value": {
            "total-intensity": {
                "units": "nT",
                "value": 123 //Return this*****************
            },
            "declination": {
                "units": "deg (east)",
                "value": -123 //Return this*****************
            },
            "inclination": {
                "units": "deg (down)",
                "value": 123 //Return this*****************
            },
            "north-intensity": {
                "units": "nT",
                "value": 123
            },
            "east-intensity": {
                "units": "nT",
                "value": -123
            },
            "vertical-intensity": {
                "units": "nT",
                "value": 123
            },
            "horizontal-intensity": {
                "units": "nT",
                "value": 123
            }
        },
        "secular-variation": {
            "total-intensity": {
                "units": "nT/y",
                "value": 123
            },
            "declination": {
                "units": "arcmin/y (east)",
                "value": 123
            },
            "inclination": {
                "units": "arcmin/y (down)",
                "value": 123
            },
            "north-intensity": {
                "units": "nT/y",
                "value": 123
            },
            "east-intensity": {
                "units": "nT/y",
                "value": 123
            },
            "vertical-intensity": {
                "units": "nT/y",
                "value": 123
            },
            "horizontal-intensity": {
                "units": "nT/y",
                "value": 123
            }
        }
    }
}

Моя попытка синтаксического анализа в настоящее время выглядит так:

public void onResponse(JSONObject response) {
                        try {
                            JSONObject jsonObject = response;
                            String totalIntensity = jsonObject.getJSONObject("field-value").getJSONObject("total-intensity").getString("value");
                            String declination = jsonObject.getJSONObject("field-value").getJSONObject("declination").getString("value");
                            String inclination = jsonObject.getJSONObject("field-value").getJSONObject("inclination").getString("value");


                        } catch (JSONException e) {
                            Log.d("geoData", "Error recorded");
                            e.printStackTrace();
                        }
                    }

Я совершенно не прав? Надеюсь, мне очень легко меня исправить.

Ответы [ 3 ]

1 голос
/ 14 июля 2020

Я предполагаю, что ответ, который вы получаете в методе, представляет собой весь объект JSON, который вы разместили здесь.

У вас есть несколько проблем:

  1. Ваши данные не String это Double или Integer , поэтому вы должны использовать getDouble, например.
  2. Вы забыли об одном дополнительном узле geomagnetic-field-model-result.
  3. Вам не нужно назначать внутренний JSONObject jsonObject, вы можете просто использовать ответ.

Чтобы получить значения, вы должны:

public void onResponse(JSONObject response) {
    try {
        // JSONObject jsonObject = response; you don't need this
        Double totalIntensity = response
            .getJSONObject("geomagnetic-field-model-result")
            .getJSONObject("field-value")
            .getJSONObject("total-intensity")
            .getDouble("value");
        Double declination = response
            .getJSONObject("geomagnetic-field-model-result")
            .getJSONObject("field-value")
            .getJSONObject("declination")
            .getDouble("value");
        Double inclination = response
            .getJSONObject("geomagnetic-field-model-result")
            .getJSONObject("field-value")
            .getJSONObject("inclination")
            .getDouble("value");

        // use it somehow
    } catch (JSONException e) {
        Log.d("geoData", "Error recorded");
        e.printStackTrace();
    }
}
0 голосов
/ 14 июля 2020

Вы можете использовать Джексона так:

import com.fasterxml.jackson.databind.ObjectMapper;

        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(input);
        System.out.println(jsonNode.get("geomagnetic-field-model-result").get("field-value").get("total-intensity").get("value"));

0 голосов
/ 14 июля 2020

Создайте схему и используйте возвращаемые значения, гораздо проще работать со схемой примера для вашего возвращенного ответа, сделанного из http://www.jsonschema2pojo.org/

    -----------------------------------com.example.Altitude.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Altitude {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Double value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Double getValue() {
return value;
}

public void setValue(Double value) {
this.value = value;
}

}
-----------------------------------com.example.Coordinates.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Coordinates {

@SerializedName("latitude")
@Expose
private Latitude latitude;
@SerializedName("longitude")
@Expose
private Longitude longitude;
@SerializedName("altitude")
@Expose
private Altitude altitude;

public Latitude getLatitude() {
return latitude;
}

public void setLatitude(Latitude latitude) {
this.latitude = latitude;
}

public Longitude getLongitude() {
return longitude;
}

public void setLongitude(Longitude longitude) {
this.longitude = longitude;
}

public Altitude getAltitude() {
return altitude;
}

public void setAltitude(Altitude altitude) {
this.altitude = altitude;
}

}
-----------------------------------com.example.Date.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Date {

@SerializedName("value")
@Expose
private String value;

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

}
-----------------------------------com.example.Declination.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Declination {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Integer value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Integer getValue() {
return value;
}

public void setValue(Integer value) {
this.value = value;
}

}
-----------------------------------com.example.Declination_.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Declination_ {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Integer value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Integer getValue() {
return value;
}

public void setValue(Integer value) {
this.value = value;
}

}
-----------------------------------com.example.EastIntensity.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class EastIntensity {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Integer value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Integer getValue() {
return value;
}

public void setValue(Integer value) {
this.value = value;
}

}
-----------------------------------com.example.EastIntensity_.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class EastIntensity_ {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Integer value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Integer getValue() {
return value;
}

public void setValue(Integer value) {
this.value = value;
}

}
-----------------------------------com.example.Example.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

@SerializedName("geomagnetic-field-model-result")
@Expose
private GeomagneticFieldModelResult geomagneticFieldModelResult;

public GeomagneticFieldModelResult getGeomagneticFieldModelResult() {
return geomagneticFieldModelResult;
}

public void setGeomagneticFieldModelResult(GeomagneticFieldModelResult geomagneticFieldModelResult) {
this.geomagneticFieldModelResult = geomagneticFieldModelResult;
}

}
-----------------------------------com.example.FieldValue.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class FieldValue {

@SerializedName("total-intensity")
@Expose
private TotalIntensity totalIntensity;
@SerializedName("declination")
@Expose
private Declination declination;
@SerializedName("inclination")
@Expose
private Inclination inclination;
@SerializedName("north-intensity")
@Expose
private NorthIntensity northIntensity;
@SerializedName("east-intensity")
@Expose
private EastIntensity eastIntensity;
@SerializedName("vertical-intensity")
@Expose
private VerticalIntensity verticalIntensity;
@SerializedName("horizontal-intensity")
@Expose
private HorizontalIntensity horizontalIntensity;

public TotalIntensity getTotalIntensity() {
return totalIntensity;
}

public void setTotalIntensity(TotalIntensity totalIntensity) {
this.totalIntensity = totalIntensity;
}

public Declination getDeclination() {
return declination;
}

public void setDeclination(Declination declination) {
this.declination = declination;
}

public Inclination getInclination() {
return inclination;
}

public void setInclination(Inclination inclination) {
this.inclination = inclination;
}

public NorthIntensity getNorthIntensity() {
return northIntensity;
}

public void setNorthIntensity(NorthIntensity northIntensity) {
this.northIntensity = northIntensity;
}

public EastIntensity getEastIntensity() {
return eastIntensity;
}

public void setEastIntensity(EastIntensity eastIntensity) {
this.eastIntensity = eastIntensity;
}

public VerticalIntensity getVerticalIntensity() {
return verticalIntensity;
}

public void setVerticalIntensity(VerticalIntensity verticalIntensity) {
this.verticalIntensity = verticalIntensity;
}

public HorizontalIntensity getHorizontalIntensity() {
return horizontalIntensity;
}

public void setHorizontalIntensity(HorizontalIntensity horizontalIntensity) {
this.horizontalIntensity = horizontalIntensity;
}

}
-----------------------------------com.example.GeomagneticFieldModelResult.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class GeomagneticFieldModelResult {

@SerializedName("model")
@Expose
private String model;
@SerializedName("model_revision")
@Expose
private String modelRevision;
@SerializedName("date")
@Expose
private Date date;
@SerializedName("coordinates")
@Expose
private Coordinates coordinates;
@SerializedName("field-value")
@Expose
private FieldValue fieldValue;
@SerializedName("secular-variation")
@Expose
private SecularVariation secularVariation;

public String getModel() {
return model;
}

public void setModel(String model) {
this.model = model;
}

public String getModelRevision() {
return modelRevision;
}

public void setModelRevision(String modelRevision) {
this.modelRevision = modelRevision;
}

public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}

public Coordinates getCoordinates() {
return coordinates;
}

public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}

public FieldValue getFieldValue() {
return fieldValue;
}

public void setFieldValue(FieldValue fieldValue) {
this.fieldValue = fieldValue;
}

public SecularVariation getSecularVariation() {
return secularVariation;
}

public void setSecularVariation(SecularVariation secularVariation) {
this.secularVariation = secularVariation;
}

}
-----------------------------------com.example.HorizontalIntensity.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class HorizontalIntensity {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Integer value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Integer getValue() {
return value;
}

public void setValue(Integer value) {
this.value = value;
}

}
-----------------------------------com.example.HorizontalIntensity_.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class HorizontalIntensity_ {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Integer value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Integer getValue() {
return value;
}

public void setValue(Integer value) {
this.value = value;
}

}
-----------------------------------com.example.Inclination.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Inclination {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Integer value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Integer getValue() {
return value;
}

public void setValue(Integer value) {
this.value = value;
}

}
-----------------------------------com.example.Inclination_.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Inclination_ {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Integer value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Integer getValue() {
return value;
}

public void setValue(Integer value) {
this.value = value;
}

}
-----------------------------------com.example.Latitude.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Latitude {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Double value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Double getValue() {
return value;
}

public void setValue(Double value) {
this.value = value;
}

}
-----------------------------------com.example.Longitude.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Longitude {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Double value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Double getValue() {
return value;
}

public void setValue(Double value) {
this.value = value;
}

}
-----------------------------------com.example.NorthIntensity.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class NorthIntensity {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Integer value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Integer getValue() {
return value;
}

public void setValue(Integer value) {
this.value = value;
}

}
-----------------------------------com.example.NorthIntensity_.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class NorthIntensity_ {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Integer value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Integer getValue() {
return value;
}

public void setValue(Integer value) {
this.value = value;
}

}
-----------------------------------com.example.SecularVariation.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class SecularVariation {

@SerializedName("total-intensity")
@Expose
private TotalIntensity_ totalIntensity;
@SerializedName("declination")
@Expose
private Declination_ declination;
@SerializedName("inclination")
@Expose
private Inclination_ inclination;
@SerializedName("north-intensity")
@Expose
private NorthIntensity_ northIntensity;
@SerializedName("east-intensity")
@Expose
private EastIntensity_ eastIntensity;
@SerializedName("vertical-intensity")
@Expose
private VerticalIntensity_ verticalIntensity;
@SerializedName("horizontal-intensity")
@Expose
private HorizontalIntensity_ horizontalIntensity;

public TotalIntensity_ getTotalIntensity() {
return totalIntensity;
}

public void setTotalIntensity(TotalIntensity_ totalIntensity) {
this.totalIntensity = totalIntensity;
}

public Declination_ getDeclination() {
return declination;
}

public void setDeclination(Declination_ declination) {
this.declination = declination;
}

public Inclination_ getInclination() {
return inclination;
}

public void setInclination(Inclination_ inclination) {
this.inclination = inclination;
}

public NorthIntensity_ getNorthIntensity() {
return northIntensity;
}

public void setNorthIntensity(NorthIntensity_ northIntensity) {
this.northIntensity = northIntensity;
}

public EastIntensity_ getEastIntensity() {
return eastIntensity;
}

public void setEastIntensity(EastIntensity_ eastIntensity) {
this.eastIntensity = eastIntensity;
}

public VerticalIntensity_ getVerticalIntensity() {
return verticalIntensity;
}

public void setVerticalIntensity(VerticalIntensity_ verticalIntensity) {
this.verticalIntensity = verticalIntensity;
}

public HorizontalIntensity_ getHorizontalIntensity() {
return horizontalIntensity;
}

public void setHorizontalIntensity(HorizontalIntensity_ horizontalIntensity) {
this.horizontalIntensity = horizontalIntensity;
}

}
-----------------------------------com.example.TotalIntensity.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class TotalIntensity {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Integer value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Integer getValue() {
return value;
}

public void setValue(Integer value) {
this.value = value;
}

}
-----------------------------------com.example.TotalIntensity_.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class TotalIntensity_ {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Integer value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Integer getValue() {
return value;
}

public void setValue(Integer value) {
this.value = value;
}

}
-----------------------------------com.example.VerticalIntensity.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class VerticalIntensity {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Integer value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Integer getValue() {
return value;
}

public void setValue(Integer value) {
this.value = value;
}

}
-----------------------------------com.example.VerticalIntensity_.java-----------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class VerticalIntensity_ {

@SerializedName("units")
@Expose
private String units;
@SerializedName("value")
@Expose
private Integer value;

public String getUnits() {
return units;
}

public void setUnits(String units) {
this.units = units;
}

public Integer getValue() {
return value;
}

public void setValue(Integer value) {
this.value = value;
}

}

Итак, теперь по схеме не меняется, возвращает значения в правильном формате

...