如何使用gson从json读取对象数组?

时间:2019-06-05 23:05:05

标签: java json gson

我已经编写了文件JSON,其中包含创建数组所需的信息

这是我正在使用的json

@model ProizvodModel
@{
    ViewData["Title"] = "Edit";
}
<style>

    select {
        font-size: x-large;
        background-color: lightcoral;
    }

    input {
        margin-left: 10px;
        padding-left: 10px;
    }

    input:read-only {
        background-color: lightgoldenrodyellow;
        border: 1px solid;
    }

    .ActiveProizvod {
        border: 5px solid green !important;
        padding: 10px;
        background-color: #d9f9d9;
    }

    .NotActiveProizvod {
        border: 5px solid red !important;
        padding: 10px;
        background-color: lightcoral;
    }
</style>
@{
    string borderColor = "NotActiveProizvod";
    if (Model.Aktivan)
    {
        borderColor = "ActiveProizvod";
    }
}
<div style="width: 1100px; margin: 20px auto; position: relative; border: 2px solid" class="@borderColor">
    <br />
    @if (!Model.Aktivan)
    {
        <button type="button" onclick="AktivirajProizvod(@Model.ROBAID)"><img src='/Images/checkmark.png' style='height: 20px'> <span style="font-weight: bolder">Aktiviraj proizvod</span></button><br /><br />
    }
    else
    {
        <button type="button" onclick="DeaktivirajProizvod(@Model.ROBAID)"><img src='~/Images/x-mark.png' style='height: 20px'> <span style="font-weight: bolder">Deaktiviraj proizvod</span></button><br /><br />
    }

    @using (Html.BeginForm("Save", "Proizvodi", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <label>RobaID: </label>@Html.TextBoxFor(c => c.ROBAID, new { @readonly = "true", @style = "width: 50px; text-align: center; padding: 0" }) <br />
        <label>KatBr: </label>@Html.TextBoxFor(p => p.KatBr, new { @style = "width: 200px" })<br />
        <label>Naziv: </label>@Html.TextBoxFor(p => p.Naziv, new { @style = "width: 300px" })<br />
        <label>JM: </label>@Html.TextBoxFor(p => p.JM, new { @style = "width: 50px; text-align: center; padding: 0" })<br />
        <label>Redirect: </label>@Html.TextBoxFor(p => p.Redirect, new { @style = "width: 200px" })<br /><br />
        <img src="@Model.Slika" id="Slika_i" style="max-width: 200px; border: 2px solid; padding: 5px" /><br /><br />
        <label>Podgrupa: </label>@Html.DropDownListFor(p => p.PodgrupaID, new SelectList(PodgrupaModel.List(), "PodgrupaID", "Naziv"))<br />
        <label>Klasifikacija: </label>@Html.DropDownListFor(p => p.Klasifikacija, new SelectList(new List<Tuple<int, string>>() { new Tuple<int, string>(0, "HOBI"), new Tuple<int, string>(1, "STANDARD"), new Tuple<int, string>(2, "PROFI") }, "Item1", "Item2"))<br />
        <label>Cenovna grupa: </label>@Html.DropDownListFor(p => p.Cenovnik_GrupaID, new SelectList(CenovnikGrupaModel.List(), "ID", "Naziv"));<br />

        <h2>Cene (bez PDV):</h2>
        Model.UcitajCene();

        for(int i = 0; i < Model.Cene.Count; i++)
        {
            <h3>@((CenovnikModel.Level)Model.Cene[i].Nivo)</h3>@Html.TextBoxFor(p => p.Cene[i].VPCena, new { @type = "number" });<br />
        }

        <div style="position: absolute; right: 0; top: 20px">
            <button id="Save_btn"><img src="~/images/save.png" style="height: 50px" /></button>
        </div>
    }
</div>

<div id="Gallery">
</div>

<div id="AB">
</div>

<script src="~/js/FileUploader.js"></script>
<script src="~/js/AlertBox.js"></script>
<script>

    var alb = new AlertBox($("#AB"));
    var ImagesArray = [];

    @foreach(string s in Galerija.Slike())
    {
        @:ImagesArray.push(`@s`);
    }
    var gal = new Gallery($("#Gallery"), ImagesArray, "/Images/");

    function DeaktivirajProizvod(RobaID) {
        $.ajax({
            type: "GET",
            url: "/Proizvodi/DeaktivirajProizvod",
            contentType: "application.json; charset-utf-8",
            dataType: "json",
            async: false,
            data: {
                "RobaID": RobaID
            },
            success: function () {
                alert("Proizvod deaktiviran!");
                window.location.reload();
            },
            error: function () {
                alert("Error");
            }
        });
}
    function AktivirajProizvod(RobaID) {
        $.ajax({
            type: "GET",
            url: "/Proizvodi/AktivirajProizvod",
            contentType: "application.json; charset-utf-8",
            dataType: "json",
            async: false,
            data: {
                "RobaID": RobaID
            },
            success: function () {
                alert("Proizvod aktiviran!");
                window.location.reload();
            },
            error: function () {
                alert("Error");
            }
        });
    }

    $(function () {
        $("#Slika_i").click(function () {
            gal.Show(function (src) {
                $("#Slika_i").attr("src", src);
                $.ajax({
                    type: "GET",
                    url: "/Proizvodi/AzurirajSliku",
                    contentType: "application.json; charset-utf-8",
                    dataType: "json",
                    async: false,
                    data: {
                        "ROBAID": @Model.ROBAID,
                        "Slika": src
                    },
                    success: function (data) {
                        alb.Show(data);
                    },
                    error: function (data) {
                        alb.Show(data);
                    }
                });
            });
        });
    });
</script>

这就是我尝试使用Java反序列化的方式

[{
  "matr": [0,0],
  "room": "b",
  "door": true,
  "respawnPoint": false
},
{
  "matr": [0,1],
  "room": "b",
  "door": false,
  "respawnPoint": false
},...
]    

但出现此错误

String path="src/main/resources/room.json";
            JsonReader reader= new JsonReader(new FileReader(path));
            SupportPosition[] a=new Gson().fromJson(path, 
SupportPosition[].class);    

2 个答案:

答案 0 :(得分:0)

您正在将文件路径作为参数传递给Gson构造函数。 您必须将JsonReader对象作为参数传递给Gson构造函数。

JsonReader reader= new JsonReader(new FileReader(path));
        SupportPosition[] a=new Gson().fromJson(reader, SupportPosition[].class);

尝试一下,让我知道。

答案 1 :(得分:0)

Parsing JSON array into java.util.List with Gson我认为您的问题已经在另一篇文章中得到了解答。看一看。

public class Human {

    String name;
    Integer age;

    //getters and setters
}

主要类别如下:

public class Solution{
 public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();
        String json = "[{\"name\":\"Dummy\", \"age\":37}, {\"name\":\"Dummy2\", \"age\":38}]";

        try {

            // 1. convert JSON array to Array objects
            Human[] HumanObjects = mapper.readValue(json, Human[].class);

            System.out.println("JSON array to Array objects...");
            for (Human Human : HumanObjects) {
                System.out.println(Human);
            }

            // 2. convert JSON array to List of objects
            List<Human> ppl2 = Arrays.asList(mapper.readValue(json, Human[].class));

            System.out.println("\nJSON array to List of objects");
            ppl2.stream().forEach(x -> System.out.println(x));

            // 3. alternative
            List<Human> pp3 = mapper.readValue(json, new TypeReference<List<Human>>() {});

            System.out.println("\nAlternative...");
            pp3.stream().forEach(x -> System.out.println(x));

        } catch (Exceptoion e) {
            e.printStackTrace();
        }

    }
    }

使用需要导入的“杰克逊”。可能添加一个Maven依赖项。让我知道是否有帮助。