У меня есть этот json файл, который я скачал онлайн:
{
"price": 1,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 0,
"highValue": 0
},
и я хочу удалить все из
"empty": [
в
],
Я потратил несколько часов на просмотр регулярных выражений, и я не могу понять, как заставить его делать то, что я хочу.
Изменить: метод Annamalai Thangaraj работает до тех пор, пока я не добавлю больше файла.
{
"price": 1,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 0,
"highValue": 0
},
{
"price": 500,
"empty": [
5,
0,
3,
6,
9
],
"lowValue": 4,
"highValue": 2
}
который теперь я получил ошибку:
Исключение в потоке "main" java.lang.ClassCastException: com.google.gson.JsonArray не может быть добавлено в com.google.gson.JsonObject
Мой код точно:
public static void go() throws IOException {
JsonObject jsonObject = (JsonObject)JsonParser.parse(new FileReader(location));
jsonObject.remove("empty");
JsonArray jsonArray = (JsonArray)JsonParser.parse(new FileReader(location));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(jsonObject.toString());
String prettyJsonString = gson.toJson(je);
FileWriter file = new FileWriter(System.getProperties().getProperty("user.home")+"\\output.json");
try {
file.write(prettyJsonString);
System.out.println("Successfully wrote JSON object to file.");
} catch (IOException e) {
e.printStackTrace();
} finally {
file.flush();
file.close();
}
}
Используйте следующий код, чтобы удалить элемент empty
с json
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("File Path"));
jsonObject .remove("empty");
После удаления empty
элемента с помощью jsonObject.toJSONString(), чтобы получить целевой JSON, теперь структура JSON будет выглядеть так:
{
"price": 1,
"lowValue": 0,
"highValue": 0
},
Используйте JSON-библиотеку, такую как Jackson:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
public class JsonDelete {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"key\":\"value\",\"empty\":[]}";
ObjectNode node = (ObjectNode) mapper.readTree(json);
node.remove("empty");
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node));
}
}
Выходы:
{
"key" : "value"
}
Вы также можете проанализировать свой json, игнорируя некоторые поля. Посмотрите на этот пример:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@JsonIgnoreProperties(value = { "empty" })
public class Item {
private long price;
private long lowValue;
private long highValue;
public long getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
public long getLowValue() {
return lowValue;
}
public void setLowValue(long lowValue) {
this.lowValue = lowValue;
}
public long getHighValue() {
return highValue;
}
public void setHighValue(long highValue) {
this.highValue = highValue;
}
@Override
public String toString() {
return "Item [price=" + price + ", lowValue=" + lowValue + ", highValue=" + highValue + "]";
}
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String file = "c:\\json";
ObjectMapper mapper = new ObjectMapper();
Item[] items = mapper.readValue(new File(file), Item[].class);
for (Item item : items) {
System.out.println(item);
}
}
}
c:\json содержит:
[
{
"price": 1,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 0,
"highValue": 0
},
{
"price": 2,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 3,
"highValue": 4
}
]
Выход:
Item [price=1, lowValue=0, highValue=0]
Item [price=2, lowValue=3, highValue=4]
Если вы положите '[' в начале и ''] в конце json файла, он станет действительным json файлом. Как и в вашем json файле, должно быть.
[
{
"price": 1,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 0,
"highValue": 0
},
{
"price": 500,
"empty": [
5,
0,
3,
6,
9
],
"lowValue": 4,
"highValue": 2
}
]
Таким образом, финальная программа будет выглядеть так:
public class ReadJSONFromFile {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("locationOfFIle"));
JSONArray array = (JSONArray) obj;
FileWriter file = new FileWriter("locationOfFIle");
for (int index = 0; index < array.size(); ++index) {
JSONObject jsonObject = (JSONObject) array.get(index);
jsonObject.remove("empty");
file.write(jsonObject.toJSONString());
file.flush();
if (index == array.size() - 1)
file.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}