'NextTo' signifies which regions.
Stuck on parsing.
Yes, your pseudo-code is the right way to go.
Start by deserializing your JSON string with Jackson (find the appropriate "model", e.g. nextTo can be mapped to a Map<Integer, List<Integer>>) then implement your pseudo-code.
Deserialise object using org.json,
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class DesrialiseJSON {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
//json string
String stringToParse="{\"Regions\" : [{\"regionId\" : 5,\"name\" : \"South Korea\"},{\"regionId\" : 6,\"name\" : \"North Korea\"},{ }],\"nextTo\" : { \"5\" : [6], \"6\" : [5]}}";
try {
//convert to json object
JSONObject json = (JSONObject) parser.parse(stringToParse);
System.out.println(checkNextTo(json));
} catch (ParseException e) {
e.printStackTrace();
}
}
public static boolean checkNextTo(JSONObject json) {
//regions array
JSONArray regionArr=(JSONArray) json.get("Regions");
// Find the id of region1 in the "region" part of the JSON
long regionId1=(Long) ((JSONObject) regionArr.get(0)).get("regionId");
// Find the id of region2 in the "region" part of the JSON
long regionId2=(Long) ((JSONObject) regionArr.get(1)).get("regionId");
JSONObject nextTo=(JSONObject) json.get("nextTo");
Long nextToReg1=(Long) ((JSONArray) nextTo.get(String.valueOf(regionId1))).get(0);
Long nextToReg2=(Long) ((JSONArray) nextTo.get(String.valueOf(regionId2))).get(0);
// Check region1's nextTo regions in the "nextTo" section ofJSON
// If region2 id is in region1 id's nextTo {
//return True
// Else
return regionId1==nextToReg2 || regionId2==nextToReg1;
}
}
Related
I have a JsonObject named "mapping" with the following content:
{
"client": "127.0.0.1",
"servers": [
"8.8.8.8",
"8.8.4.4",
"156.154.70.1",
"156.154.71.1"
]
}
I know I can get the array "servers" with:
mapping.get("servers").getAsJsonArray()
And now I want to parse that JsonArray into a java.util.List...
What is the easiest way to do this?
Definitely the easiest way to do that is using Gson's default parsing function fromJson().
There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType (e.g., any List), which is fromJson(JsonElement json, Type typeOfT).
In your case, you just need to get the Type of a List<String> and then parse the JSON array into that Type, like this:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
JsonElement yourJson = mapping.get("servers");
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> yourList = new Gson().fromJson(yourJson, listType);
In your case yourJson is a JsonElement, but it could also be a String, any Reader or a JsonReader.
You may want to take a look at Gson API documentation.
Below code is using com.google.gson.JsonArray.
I have printed the number of element in list as well as the elements in List
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
static String str = "{ "+
"\"client\":\"127.0.0.1\"," +
"\"servers\":[" +
" \"8.8.8.8\"," +
" \"8.8.4.4\"," +
" \"156.154.70.1\"," +
" \"156.154.71.1\" " +
" ]" +
"}";
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(str);
JsonArray jsonArr = jo.getAsJsonArray("servers");
//jsonArr.
Gson googleJson = new Gson();
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
System.out.println("List size is : "+jsonObjList.size());
System.out.println("List Elements are : "+jsonObjList.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT
List size is : 4
List Elements are : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]
I read solution from official website of Gson at here
And this code for you:
String json = "{"client":"127.0.0.1","servers":["8.8.8.8","8.8.4.4","156.154.70.1","156.154.71.1"]}";
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
JsonArray jsonArray = jsonObject.getAsJsonArray("servers");
String[] arrName = new Gson().fromJson(jsonArray, String[].class);
List<String> lstName = new ArrayList<>();
lstName = Arrays.asList(arrName);
for (String str : lstName) {
System.out.println(str);
}
Result show on monitor:
8.8.8.8
8.8.4.4
156.154.70.1
156.154.71.1
I was able to get the list mapping to work with just using #SerializedName for all fields.. no logic around Type was necessary.
Running the code - in step #4 below - through the debugger, I am able to observe that the List<ContentImage> mGalleryImages object populated with the JSON data
Here's an example:
1. The JSON
{
"name": "Some House",
"gallery": [
{
"description": "Nice 300sqft. den.jpg",
"photo_url": "image/den.jpg"
},
{
"description": "Floor Plan",
"photo_url": "image/floor_plan.jpg"
}
]
}
2. Java class with the List
public class FocusArea {
#SerializedName("name")
private String mName;
#SerializedName("gallery")
private List<ContentImage> mGalleryImages;
}
3. Java class for the List items
public class ContentImage {
#SerializedName("description")
private String mDescription;
#SerializedName("photo_url")
private String mPhotoUrl;
// getters/setters ..
}
4. The Java code that processes the JSON
for (String key : focusAreaKeys) {
JsonElement sectionElement = sectionsJsonObject.get(key);
FocusArea focusArea = gson.fromJson(sectionElement, FocusArea.class);
}
Kotlin Extension
for Kotlin developers you can use this extension
inline fun <reified T> String.convertToListObject(): List<T>? {
val listType: Type = object : TypeToken<List<T?>?>() {}.type
return Gson().fromJson<List<T>>(this, listType)
}
Given you start with mapping.get("servers").getAsJsonArray(), if you have access to Guava Streams, you can do the below one-liner:
List<String> servers = Streams.stream(jsonArray.iterator())
.map(je -> je.getAsString())
.collect(Collectors.toList());
Note StreamSupport won't be able to work on JsonElement type, so it is insufficient.
I've got a broblem wih JSON parser.
Here is the JSON response from server.
{
"coord" : {"lon":37.62,"lat":55.75},
"weather":[{"id":803,"main":"Clouds","description":"test","icon":"04d"}],
"base" :"stations",
"main" :{"temp":12.76,"pressure":1007,"humidity":93,"tempmin":12,"tempmax":14},
"visibility":6000,
"wind" :{"speed":4,"deg":300},
"clouds" :{"all":75},
"dt":1504881000,
"sys" :{"type":1,"id":7325,"message":0.0064,"country":"RU","sunrise":1504838942,"sunset":1504886617},
"id" :524901,
"name" :"City",
"cod" :200
}
And java code ....
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.*;
public static void main(String[] args) throws JSONException {
try {
JsonParser parser = new JsonParser();
JsonObject json = parser.parse("JSON responce here").getAsJsonObject();
JsonArray weather = json.get("weather").getAsJsonArray(); //no problem
int visibility = json.get("visibility").getAsInt();
int id = json.get("id").getAsInt();
int dt = json.get("dt").getAsInt();
String name = json.get("name").getAsString();
JsonArray clouds = json.get("clouds").getAsJsonArray(); //here is the problem
JsonArray main = json.get("main").getAsJsonArray(); //here is the problem
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is ... when I compile I've got java.lang.IllegalStateException: This is not a JSON Array. on JsonArray clouds = json.get("clouds").getAsJsonArray(); and others lines like this.
BUT JsonArray weather = json.get("weather").getAsJsonArray(); is OK...
I don't understand what is happening... but the array "weather" node has no problem... totally. Please, help me... what's wrong?
Because it is a Json Object
JsonObject json = json.get("clouds").getAsJsonObject()
It will work...
Or you can change the data as given below
{
"coord" : {"lon":37.62,"lat":55.75},
"weather":{"id":803,"main":"Clouds","description":"test","icon":"04d"},
"base" :"stations",
"main" :{"temp":12.76,"pressure":1007,"humidity":93,"tempmin":12,"tempmax":14},
"visibility":6000,
"wind" :{"speed":4,"deg":300},
"clouds" :[{"all":75}],
"dt":1504881000,
"sys" :{"type":1,"id":7325,"message":0.0064,"country":"RU","sunrise":1504838942,"sunset":1504886617},
"id" :524901,
"name" :"City",
"cod" :200
}
I am coding a feature in which I read and write back json. However I can read the json elements from a file but can't edit the same loaded object. Here is my code which I am working on.
InputStream inp = new FileInputStream(jsonFilePath);
JsonReader reader = Json.createReader(inp);
JsonArray employeesArr = reader.readArray();
for (int i = 0; i < 2; i++) {
JsonObject jObj = employeesArr.getJsonObject(i);
JsonObject teammanager = jObj.getJsonObject("manager");
Employee manager = new Employee();
manager.name = teammanager.getString("name");
manager.emailAddress = teammanager.getString("email");
System.out.println("uploading File " + listOfFiles[i].getName());
File file = insertFile(...);
JsonObject tmpJsonValue = Json.createObjectBuilder()
.add("fileId", file.getId())
.add("alternativeLink", file.getAlternateLink())
.build();
jObj.put("alternativeLink", tmpJsonValue.get("alternativeLink")); <-- fails here
}
I get the following exception when I run it.
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractMap.put(AbstractMap.java:203)
at com.mongodb.okr.DriveQuickstart.uploadAllFiles(DriveQuickstart.java:196)
at com.mongodb.okr.App.main(App.java:28)
The javadoc of JsonObject states
JsonObject class represents an immutable JSON object value (an
unordered collection of zero or more name/value pairs). It also
provides unmodifiable map view to the JSON object name/value mappings.
You can't modify these objects.
You'll need to create a copy. There doesn't seem to be a direct way to do that. It looks like you'll need to use Json.createObjectBuilder() and build it yourself (see the example in the javadoc linked).
As answered by Sotirios, you can use JsonObjectBuilders.
To insert value into JsonObject, you can use method:
private JsonObject insertValue(JsonObject source, String key, String value) {
JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add(key, value);
source.entrySet().
forEach(e -> builder.add(e.getKey(), e.getValue()));
return builder.build();
}
To insert JsonObject into JsonObject, you can use method:
private JsonObject insertObject(JsonObject parent, JsonObject child, String childName) {
JsonObjectBuilder child_builder = Json.createObjectBuilder();
JsonObjectBuilder parent_builder = Json.createObjectBuilder();
parent.entrySet().
forEach(e -> parent_builder.add(e.getKey(), e.getValue()));
child.entrySet().
forEach(e -> child_builder.add(e.getKey(), e.getValue()));
parent_builder.add(childName, child_builder);
return parent_builder.build();
}
Please note, if you change the child JsonObject after inserting it into another "parent" JsonObject, it will have no effect on the "parent" JsonObject.
JsonObject is immutable so you cannot modify the object , you can use this example and try to inspire from it : creation of a new JsonObject who contains the same values and add some elements to it ..
Example :
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonReader;
import javax.json.JsonValue;
public class Jsonizer {
public static void main(String[] args) {
try {
String s = "{\"persons\": [ {\"name\":\"oussama\",\"age\":\"30\"}, {\"name\":\"amine\",\"age\":\"25\"} ]}";
InputStream is = new ByteArrayInputStream(s.getBytes());
JsonReader jr = Json.createReader(is);
JsonObject jo = jr.readObject();
System.out.println("Before :");
System.out.println(jo);
JsonArray ja = jo.getJsonArray("persons");
InputStream targetStream = new ByteArrayInputStream("{\"name\":\"sami\",\"age\":\"50\"}".getBytes());
jr = Json.createReader(targetStream);
JsonObject newJo = jr.readObject();
JsonArrayBuilder jsonArraybuilder = Json.createArrayBuilder();
jsonArraybuilder.add(newJo);
for (JsonValue jValue : ja) {
jsonArraybuilder.add(jValue);
}
ja = jsonArraybuilder.build();
JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
jsonObjectBuilder.add("persons", ja);
JsonObject jsonAfterAdd = jsonObjectBuilder.build();
System.out.println("After");
System.out.println(jsonAfterAdd.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Output :
Before :
{"persons":[{"name":"oussama","age":"30"},{"name":"amine","age":"25"}]}
After
{"persons":[{"name":"sami","age":"50"},{"name":"oussama","age":"30"},{"name":"amine","age":"25"}]}
Try using the simple JSONObject, not javax.
import org.json.JSONObject;
You can download the jar or include it in your maven or gradle like so:
dependencies {
compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
}
also see:
creating json string using JSONObject and JSONArray
I have a JsonObject named "mapping" with the following content:
{
"client": "127.0.0.1",
"servers": [
"8.8.8.8",
"8.8.4.4",
"156.154.70.1",
"156.154.71.1"
]
}
I know I can get the array "servers" with:
mapping.get("servers").getAsJsonArray()
And now I want to parse that JsonArray into a java.util.List...
What is the easiest way to do this?
Definitely the easiest way to do that is using Gson's default parsing function fromJson().
There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType (e.g., any List), which is fromJson(JsonElement json, Type typeOfT).
In your case, you just need to get the Type of a List<String> and then parse the JSON array into that Type, like this:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
JsonElement yourJson = mapping.get("servers");
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> yourList = new Gson().fromJson(yourJson, listType);
In your case yourJson is a JsonElement, but it could also be a String, any Reader or a JsonReader.
You may want to take a look at Gson API documentation.
Below code is using com.google.gson.JsonArray.
I have printed the number of element in list as well as the elements in List
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
static String str = "{ "+
"\"client\":\"127.0.0.1\"," +
"\"servers\":[" +
" \"8.8.8.8\"," +
" \"8.8.4.4\"," +
" \"156.154.70.1\"," +
" \"156.154.71.1\" " +
" ]" +
"}";
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(str);
JsonArray jsonArr = jo.getAsJsonArray("servers");
//jsonArr.
Gson googleJson = new Gson();
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
System.out.println("List size is : "+jsonObjList.size());
System.out.println("List Elements are : "+jsonObjList.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT
List size is : 4
List Elements are : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]
I read solution from official website of Gson at here
And this code for you:
String json = "{"client":"127.0.0.1","servers":["8.8.8.8","8.8.4.4","156.154.70.1","156.154.71.1"]}";
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
JsonArray jsonArray = jsonObject.getAsJsonArray("servers");
String[] arrName = new Gson().fromJson(jsonArray, String[].class);
List<String> lstName = new ArrayList<>();
lstName = Arrays.asList(arrName);
for (String str : lstName) {
System.out.println(str);
}
Result show on monitor:
8.8.8.8
8.8.4.4
156.154.70.1
156.154.71.1
I was able to get the list mapping to work with just using #SerializedName for all fields.. no logic around Type was necessary.
Running the code - in step #4 below - through the debugger, I am able to observe that the List<ContentImage> mGalleryImages object populated with the JSON data
Here's an example:
1. The JSON
{
"name": "Some House",
"gallery": [
{
"description": "Nice 300sqft. den.jpg",
"photo_url": "image/den.jpg"
},
{
"description": "Floor Plan",
"photo_url": "image/floor_plan.jpg"
}
]
}
2. Java class with the List
public class FocusArea {
#SerializedName("name")
private String mName;
#SerializedName("gallery")
private List<ContentImage> mGalleryImages;
}
3. Java class for the List items
public class ContentImage {
#SerializedName("description")
private String mDescription;
#SerializedName("photo_url")
private String mPhotoUrl;
// getters/setters ..
}
4. The Java code that processes the JSON
for (String key : focusAreaKeys) {
JsonElement sectionElement = sectionsJsonObject.get(key);
FocusArea focusArea = gson.fromJson(sectionElement, FocusArea.class);
}
Kotlin Extension
for Kotlin developers you can use this extension
inline fun <reified T> String.convertToListObject(): List<T>? {
val listType: Type = object : TypeToken<List<T?>?>() {}.type
return Gson().fromJson<List<T>>(this, listType)
}
Given you start with mapping.get("servers").getAsJsonArray(), if you have access to Guava Streams, you can do the below one-liner:
List<String> servers = Streams.stream(jsonArray.iterator())
.map(je -> je.getAsString())
.collect(Collectors.toList());
Note StreamSupport won't be able to work on JsonElement type, so it is insufficient.
I want the following json ,where List<form> will have list of form_id,form_name, how can I convert this using jsonobject, I am not getting the proper json output. Please help me with this.
Json:
{
"forms": [
{ "form_id": "1", "form_name": "test1" },
{ "form_id": "2", "form_name": "test2" }
]
}
The above is the json structure that i need it for a list.Where id ,name is a list from form object
public static JSONObject getJsonFromMyFormObject(List<Form> form) {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = null;
System.out.println(form.size());
for (int i = 0; i < form.size(); i++) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("form", jsonArray);
return responseDetailsJson;
}
Facing issue here not getting output as a list
The code in the original question is close to achieving the described desired result. Just move the JSONArray instance creation outside of the loop.
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class Foo
{
public static JSONObject getJsonFromMyFormObject(List<Form> form)
{
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < form.size(); i++)
{
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
jsonArray.add(formDetailsJson);
}
responseDetailsJson.put("forms", jsonArray);
return responseDetailsJson;
}
public static void main(String[] args)
{
List<Form> forms = new ArrayList<Form>();
forms.add(new Form("1", "test1"));
forms.add(new Form("2", "test2"));
JSONObject jsonObject = getJsonFromMyFormObject(forms);
System.out.println(jsonObject);
}
}
class Form
{
String id;
String name;
Form(String i, String n)
{
id = i;
name = n;
}
String getId()
{
return id;
}
String getName()
{
return name;
}
}
Properbly http://www.roseindia.net/tutorials/json/jsonobject-java-example.shtml will help.
According the comment from Tushar, here the extract from the aboved linked website:
Now in this part you will study how to use JSON in Java.
To have functionality of JSON in java you must have JSON-lib. JSON-lib also
requires following "JAR" files:
commons-lang.jar
commons-beanutils.jar
commons-collections.jar
commons-logging.jar
ezmorph.jar
json-lib-2.2.2-jdk15.jar
JSON-lib is a java library for that transforms beans, collections, maps, java arrays and XML to JSON and
then for retransforming them back to beans, collections, maps and
others. In this example we are going to use JSONObject class for
creating an object of JSONObject and then we will print these object
value. For using JSONObject class we have to import following package
"net.sf.json". To add elements in this object we have used put()
method. Here is the full example code of FirstJSONJava.java is as
follows:
FirstJSONJava.java
import net.sf.json.JSONObject;
public class FirstJSONJava
{
public static void main(String args[])
{
JSONObject object=new JSONObject();
object.put("name","Amit Kumar");
object.put("Max.Marks",new Integer(100));
object.put("Min.Marks",new Double(40));
object.put("Scored",new Double(66.67));
object.put("nickname","Amit");
System.out.println(object);
}
}
To run this example you have to follow these few steps as follows:
Download JSON-lib jar and other supporting Jars
Add these jars to your classpath
Create and save FirstJSONJava.java
Compile it and execute it.