【问题标题】:So I am trying to create this json file using gson所以我正在尝试使用 gson 创建这个 json 文件
【发布时间】:2021-01-04 16:05:40
【问题描述】:

这是我想用我的 Java 代码创建的代码。我没有做任何详细的事情。只是想通过从 java 中解析 json 来刷新自己。

[{"county":"Jefferson",
    "houses":\[
        {"squareFeet":1100,
        "bedrooms":2,
        "bathrooms":2,
        "internet":"y",
        "location":"Country"
        },
        {"squareFeet":750,
        "bedrooms":1,
        "bathrooms":1,
        "internet":"n",
        "location":"Town"
        }
    \]
}]

目前我的 Java 代码如下所示。

使用下面的这段代码,除了第一个对象和房屋数组的标题之外,我已经接近了它。

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;

public class HousesToJSON {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        JSONArray houses = new JSONArray();

        House houseOne = createHouseObjectOne();
        House houseTwo = createHouseObjectTwo();

        houses.add(houseOne);
        houses.add(houseTwo);

        try (FileWriter writer = new FileWriter("houses.json")) {
            gson.toJson(houses, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static House createHouseObjectOne() {
        House house = new House();

        house.setSquareFeet(1100);
        house.setBedrooms(2);
        house.setBathrooms(2);
        house.setInternet('y');
        house.setLocation("Country");

        return house;
    }

    private static House createHouseObjectTwo() {
        House house = new House();

        house.setSquareFeet(750);
        house.setBedrooms(2);
        house.setBathrooms(1);
        house.setInternet('y');
        house.setLocation("Town");

        return house;
    }
}

这会在下面创建文件。

[
  {
    "squareFeet": 1100,
    "bedrooms": 2,
    "bathrooms": 2,
    "internet": "y",
    "location": "Country"
  },
  {
    "squareFeet": 750,
    "bedrooms": 2,
    "bathrooms": 1,
    "internet": "y",
    "location": "Town"
  }
]

我在这方面还很陌生,任何帮助都将不胜感激。

【问题讨论】:

  • 您想要生成的不是有效的 JSON,或者您可能有错字。另外,Google Gson 和 org.json 是两个不同的东西,不应该混在一起。

标签: java json gson


【解决方案1】:

类似的东西应该为您的 JSON 示例提供必要的对象:

package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class CountyContainer {

 @SerializedName("county")
 @Expose
 private String county;
 @SerializedName("houses")
 @Expose
 private List<House> houses = null;

 public String getCounty() {
  return county;
 }

 public void setCounty(String county) {
  this.county = county;
 }

 public List<House> getHouses() {
  return houses;
 }

 public void setHouses(List<House> houses) {
  this.houses = houses;
 }
}

package com.example;

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

public class House {

 @SerializedName("squareFeet")
 @Expose
 private Integer squareFeet;
 @SerializedName("bedrooms")
 @Expose
 private Integer bedrooms;
 @SerializedName("bathrooms")
 @Expose
 private Integer bathrooms;
 @SerializedName("internet")
 @Expose
 private String internet;
 @SerializedName("location")
 @Expose
 private String location;

 public Integer getSquareFeet() {
  return squareFeet;
 }

 public void setSquareFeet(Integer squareFeet) {
  this.squareFeet = squareFeet;
 }

 public Integer getBedrooms() {
  return bedrooms;
 }

 public void setBedrooms(Integer bedrooms) {
  this.bedrooms = bedrooms;
 }

 public Integer getBathrooms() {
  return bathrooms;
 }

 public void setBathrooms(Integer bathrooms) {
  this.bathrooms = bathrooms;
 }

 public String getInternet() {
  return internet;
 }

 public void setInternet(String internet) {
  this.internet = internet;
 }

 public String getLocation() {
  return location;
 }

 public void setLocation(String location) {
  this.location = location;
 }
}

您可以使用此在线服务并选择 GSON 注释样式自己生成这些:
http://www.jsonschema2pojo.org/

创建对象后,您可以使用以下方法将这些对象写入 JSON 文件:

final Gson gson = new Gson();
try (final FileWriter writer = new FileWriter("houses.json")) {
 gson.toJson(houses, writer); // houses refers to your object containing the List of House objects and the country
} catch (final IOException e) {
 // Handle exceptions here
}

或者,您也可以将 JSON 数据放入 String

String json = gson.toJson(houses);

有关 GSON 功能的更多信息,请查看官方文档:
https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/module-summary.html

【讨论】:

    【解决方案2】:

    没有提供House 类,但我想我们可以跳过它。你正朝着正确的方向前进。只需添加另一个类:

    public class County {
        private String county;
        private List<House> houses;
    
        // getters, setters, whatever :) 
    }
    

    并创建此类的实例。设置名称(县域)和房屋并序列化为 JSON :)

    我可能会将 json 数组重命名为 JSONArray counties = new JSONArray();,您需要添加到该数组中的是某个名为“Jefferson”的县和您现在拥有的房屋列表。

    County county = new County();
    county.setCounty("Jefferson");
    
    List<House> houses = new ArrayList<>();
    houses.add(houseOne);
    houses.add(houseTwo);
    
    county.setHouses(houses);
    
    counties.add(county);
    

    这可能不是 100% 可以工作的代码,但希望这个想法是明确的 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 2022-09-23
      • 2012-11-07
      • 1970-01-01
      • 1970-01-01
      • 2014-12-08
      • 1970-01-01
      相关资源
      最近更新 更多