I've written a file JSON with the information that I need to use to create an array
This is the json that I'm using
[{
"matr": [0,0],
"room": "b",
"door": true,
"respawnPoint": false
},
{
"matr": [0,1],
"room": "b",
"door": false,
"respawnPoint": false
},...
]
and this is how I try to de-serialize it with java
String path="src/main/resources/room.json";
JsonReader reader= new JsonReader(new FileReader(path));
SupportPosition[] a=new Gson().fromJson(path,
SupportPosition[].class);
but this error appears
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $
You are passing the file path as a parameter into the Gson constructor.
You must pass the JsonReader object into the Gson constructor as a parameter.
JsonReader reader= new JsonReader(new FileReader(path));
SupportPosition[] a=new Gson().fromJson(reader, SupportPosition[].class);
try this and let me know.
Parsing JSON array into java.util.List with Gson I think your question has already been answered in a different post. Take a look into it.
public class Human {
String name;
Integer age;
//getters and setters
}
Main class is below :
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();
}
}
}
Use need to import "Jackson". Probably add a Maven dependency. Let me know if it helps.
Related
I have a method that exports every POJO person and create an array into a JSON:
Node temp = testa;
ObjectMapper mapper = new ObjectMapper();
FileWriter fileWriter = new FileWriter(Paths.get("jPerson.json").toFile(), true);
SequenceWriter seqWriter = mapper.writer().writeValuesAsArray(fileWriter);
while (temp != null) {
seqWriter.write(temp.getPersona());
temp = temp.getSuccessivo();
}
seqWriter.close();
I want to create a method that read every object of the array and print it on the screen. This is the prototype, but it prints the hashcode (Person#6a1aab78, etc.):
ObjectMapper mapper = new ObjectMapper();
try {
Persona[] pJson;
pJson = mapper.readValue(Paths.get("jPersona.json").toFile(), Persona[].class);
System.out.println(ReflectionToStringBuilder.toString(pJson));
} catch (IOException e) {
e.printStackTrace();
}
ReflectionToStringBuilder.toString(Object) doesn't create a "deep" toString method. In your case you could just call Arrays.toString(pJson) and it would have the same result.
Easiest solution is to just override toString in Persona.
public class Persona {
#Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}
System.out.println(Arrays.toString(pJson));
Or you use a Stream to join all the values in the pJson array to one String.
System.out.println('[' + Arrays.stream(pJson)
.map(ReflectionToStringBuilder::toString)
.collect(Collectors.joining(", "))+']');
You can do it with ObjectMapper.
ObjectMapper mapper = new ObjectMapper();
// pretty print
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pJson);
System.out.println(json);
Reference: https://mkyong.com/java/how-to-enable-pretty-print-json-output-jackson/
If you want to print your POJO Persona as JSON, you can use Jackson's ObjectMapper to serialize to a JsonNode and use JsonNode#toString():
final Persona persona = ...;
final JsonNode json = objectMapper.readValue(persona, JsonNode.class);
System.out.println(json);
If you want to print multiple Persona objects, you can iterate:
for(final Persona persona : personas) {
final JsonNode json = objectMapper.readValue(persona, JsonNode.class);
System.out.println(json);
}
or, even better, serialize once and iterate:
final Persona[] personas = ...;
final JsonNode jsonArray = objectMapper.valueToTree(personas);
// Check may not be necessary.
if(json.isArray()) {
// JsonNode implements Iterable.
for(final JsonNode jsonNode : jsonArray) {
System.out.println(jsonNode);
}
}
I haven't been programming for a long time but I like it and trying to get back on track. So please excuse the nature of the problem/question here.
What I need is pretty simple in my opinion but i'm mostly struggling with using gson and json-simple to read my json file, one at a time, and be able to retrieve the values.
I have seen many approaches on here but as I said been a while and I have not done Java a lot in my career. So need some guidance/explanation on the best approach.
JSON:
[{ "car": "Toyota", "colour": "red", "qty": "1","date_manufactured":"12972632260006" }, { "car": "Hyundai", "colour": "red", "qty": "2","date_manufactured":"1360421626000" }, { "car": "Kia", "colour": "blue", "qty": "2", "date_manufactured":"1265727226000"}, ]
Any help to put me on the right track is appreciated!
Create a POJO class to represent your JSON data:
public class CarInfo {
String car;
String colour;
String qty;
String date_manufactured;
}
Use GSON to parse JSON String Array
String carInfoJson = "[{ \"car\": \"Toyota\", \"colour\": \"red\",\"qty\": \"1\",\"date_manufactured\":\"12972632260006\" }, { \"car\":\"Hyundai\", \"colour\":\"red\",\"qty\":\"2\",\"date_manufactured\":\"1360421626000\" }]";
Gson gson = new Gson();
CarInfo[] carInfoArray = gson.fromJson(carInfoJson, CarInfo[].class);
Use GSON to parse JSON String Array from a file
String carInfoJson= new String(Files.readAllBytes(Paths.get("filename.txt")));
Gson gson = new Gson();
CarInfo[] carInfoArray = gson.fromJson(carInfoJson, CarInfo[].class);
Use GSON to parse JSON String Array from a file using BufferedReader
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
Gson gson = new Gson();
CarInfo[] carInfoArray = gson.fromJson(reader, CarInfo[].class);
} catch (FileNotFoundException ex) {
...
} finally {
...
}
Use GSON to parse JSON String Array from a file using JsonReader in stream mode
try {
InputStream stream = new FileInputStream("c:\\filename.txt");
JsonReader reader = new JsonReader(new InputStreamReader(stream, "UTF-8"));
Gson gson = new Gson();
// Read file in stream mode
reader.beginArray();
while (reader.hasNext()) {
CarInfo carInfo = gson.fromJson(reader, CarInfo.class);
}
reader.endArray();
reader.close();
} catch (UnsupportedEncodingException ex) {
...
} catch (IOException ex) {
...
}
I'm using json-simple to explain how to do this. Your json is a JSONArray (because it starts and ends with square brackets) with JSONObject (curly brackets with pair list) inside so first you've to extract the array using a JSONParser and then you can easily iterate over it and get fields from each JSONObject.
Here is a simple example it just shows you an easy and understandable way:
String json = "[{ \"car\": \"Toyota\", \"colour\": \"red\", \"qty\": \"1\",\"date_manufactured\":\"12972632260006\" }, { \"car\": \"Hyundai\", \"colour\": \"red\", \"qty\": \"2\",\"date_manufactured\":\"1360421626000\" }]";
JSONParser parser = new JSONParser();
try {
/* It's a JSONArray first. */
JSONArray tmpArr = (JSONArray)parser.parse(json);
for(Object obj : tmpArr){
/* Extract each JSONObject */
JSONObject tmpObj = (JSONObject) obj;
System.out.println(tmpObj.get("car"));
System.out.println(tmpObj.get("colour"));
System.out.println(tmpObj.get("qty"));
System.out.println(tmpObj.get("date_manufactured"));
}
} catch (ParseException e) {
e.printStackTrace();
}
Note that you can use Gson, it's much more complete then json-simple but a little bit trickier.
I am returning an JSON array which contains many objects, I'm looking to be able to search the attributes in each object and then return the objects that meet this criteria.
I am able to return the JSON array but I'm having trouble on how to then search through the objects to match the attribute values to a given value.
Some example values from the array:
[
{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"136199","timeStamp":1.483384640123117E9,"uID":"136199_3_10"},
{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"136199","timeStamp":1.483379834470379E9,"uID":"136199_3_10"},
{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"136199","timeStamp":1.483384639621985E9,"uID":"136199_3_10"}
]
I'm using the following code to return the array, which works as expected:
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonArray rootArr = root.getAsJsonArray();
The following block of code is what I'm using to search through an object for the given attribute value, this code works when only an object is returned but gives an error when the whole array is returned:
JsonObject rootObj = rootArr.getAsJsonObject();
for (String attribute : attributes) {
System.out.println(rootObj.get(attribute).getAsString());
}
It is giving the error:
java.lang.IllegalStateException: Not a JSON Object:
I've tried changing rootObj.get(attribute) to rootArr.get(attribute) but that returns the error:
incompatible types: java.lang.String cannot be converted to int
This is the method call:
method("136199", Arrays.asList("blobJson", "deviceMfg", "uID"));
Method declaration:
void method(String sensor, List<String> attributes)
The issue is that you're trying to treat JsonArray to JsonObject. Try the below code and see if it works for you. Point of interest for now is - JsonObject rootObj = rootArr.get(0).getAsJsonObject();
public static void main(String[] args) {
String json = "[{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483384640123117E9,\"uID\":\"136199_3_10\"},{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483379834470379E9,\"uID\":\"136199_3_10\"},{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483384639621985E9,\"uID\":\"136199_3_10\"}]";
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(json);
JsonArray rootArr = root.getAsJsonArray();
JsonObject rootObj = rootArr.get(0).getAsJsonObject();
rootObj.entrySet().forEach(entry -> System.out.println(entry.getKey()+": "+entry.getValue().getAsString()));
}
Here is what you can try
try {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
Log.e("JSON Count", jsonArray.get(i).toString());
}
} catch (Exception e) {
}
I've a JsonArray like:
"fields" : [
{
"name":"First Name",
"id":1
},
{
"name":"Middle Name",
"id":2
},
{
"name":"Last Name",
"id":3
}
]
I want to remove second JsonObject from above JsonArray. In order to do that I' wrote following code:
JsonArray fieldsObject =jsonObject.getJsonArray("fields");
fieldsObject.remove(fieldsObject.getJsonObject(2));
But second line throws error: java.lang.UnsupportedOperationException
Is there any way, I can remove JsonObject from a JsonArray?
You can not remove element from JsonArray as it does not support remove() method:
private static final class JsonArrayImpl extends AbstractList<JsonValue> implements JsonArray {
And remove() method's implementation comes from AbstractList :
public E remove(int index) {
throw new UnsupportedOperationException();
}
Instead why don't you create a separate data strucure array or list to hold the objects that you want?
By the way, the purpose of using JsonArray is to load json data in object form that is why it supports read methods but does not support modifications on the loaded data structure.
May be Your JsonElement or JSONArray is null.
getJsonObject returns a JSONObject.
the remove method want int.
UnsupportedOperationException
if removing is not supported.
Try This :
JSONArray fieldsObject =jsonObject.getJsonArray("fields");
fieldsObject.remove(int index);
OR
JSONArray result = new JSONArray();
for(int i=0;i<fieldsObject.length();i++)
{
if(i!=2)
{
result.put(fieldsObject.get(i));
}
}
and assign result to original one
fieldsObject=result;
gson library
Remove works for gson library version 2.3.1
public static void main(String[] args) throws Exception {
String s = "{ \"fields\" : [ "+
" {\"name\":\"First Name\",\"id\":1},"+
"{\"name\":\"Middle Name\",\"id\":2},"+
"{\"name\":\"Last Name\",\"id\":3}"+
"]}";
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(s).getAsJsonObject();
System.out.println("original object:"+json);
JsonArray fieldsObject = json.getAsJsonArray("fields");
System.out.println("Before removal :"+fieldsObject);
Object remove = fieldsObject.remove(1);
System.out.println("After removal :"+fieldsObject);
}
Output:
original object:{"fields":[{"name":"First Name","id":1},{"name":"Middle Name","id":2},{"name":"Last Name","id":3}]}
Before removal :[{"name":"First Name","id":1},{"name":"Middle Name","id":2},{"name":"Last Name","id":3}]
After removal :[{"name":"First Name","id":1},{"name":"Last Name","id":3}]
org.json library
Remove works for org.json library
public static void main(String[] args) throws Exception {
String s = "{ \"fields\" : [ "+
" {\"name\":\"First Name\",\"id\":1},"+
"{\"name\":\"Middle Name\",\"id\":2},"+
"{\"name\":\"Last Name\",\"id\":3}"+
"]}";
JSONObject json = new JSONObject(s);
System.out.println("original object:"+json);
JSONArray fieldsObject =json.getJSONArray("fields");
System.out.println("Before removal :"+fieldsObject);
Object remove = fieldsObject.remove(1);
System.out.println("After removal :"+fieldsObject);
}
Output:
original object:{"fields":[{"name":"First Name","id":1},{"name":"Middle Name","id":2},{"name":"Last Name","id":3}]}
Before removal :[{"name":"First Name","id":1},{"name":"Middle Name","id":2},{"name":"Last Name","id":3}]
After removal :[{"name":"First Name","id":1},{"name":"Last Name","id":3}]
I tried using org.json library as mentioned by Sanj in the above post. We can remove the element from JSONArray as below. I placed the json content in the .txt file and read into the String object for constructing the JSONObject. Please refer the code below.
public class App{
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("json.txt"));
String jsonContent = "";
String jsonLine;
while((jsonLine=br.readLine())!=null){
jsonContent+=jsonLine;
}
JSONObject jObj = new JSONObject(jsonContent);
JSONArray jsonArray = jObj.getJSONArray("fields");
jsonArray.remove(1);
System.out.println(jsonArray);
}
}
I'm trying to parse the following url:
http://api.crossref.org/works?rows=2
When I parse it through Gson, I got some records but somehow some others stay null.
Here is my code:
BufferedReader in = new BufferedReader(new InputStreamReader(url_tdm.openStream(), "UTF-8"));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = in.read(chars)) != -1)
buffer.append(chars, 0, read);
String jsonLine = buffer.toString();
JsonReader reader = new JsonReader(new StringReader(jsonLine));
reader.setLenient(true); // this is for Malformed json
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create();
Crossref answer = gson.fromJson(reader, Crossref.class );
List<Items> ao = answer.message.items;
public class Crossref {
public Message message;}
public class Message {
public List<Items> items;}
public class Items {
public List<String> containerTitle;
public List<String> ISSN;
public String publisher;
public List<String> title;
public String DOI;
public String type;}
So as a result of my code above, I can get container-title, publisher and title values. But ISSN and DOIs are null.
I used a FieldNamingPolicy because "container-title" contains a dash and I could not name my field like that in java (so I wrote it as camel case containerTitle).
I am not sure if this affects DOI and ISSN records which are upper case or is it something totally different?
The best way to fix something like this is to use a gson custom deserializer
I suggest that you read this other question to see a good exemple: How do I write a custom JSON deserializer for Gson?
And you can find some other greats exemples and explanations here