How to parse json string created by stringify function in javascript? - java

I want to parse the json string in java class (.java) created by stringify() function in javascript. I know to parse the string like:
String JSON_DATA
= "{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " ]"
+ "}";
but how to parse this string?
var IO = {
//returns array with storable google.maps.Overlay-definitions
IN: function(arr, //array with google.maps.Overlays
encoded//boolean indicating whether pathes should be stored encoded
) {
var shapes = [],
goo = google.maps,
shape, tmp;
for (var i = 0; i < arr.length; i++)
{
shape = arr[i];
tmp = {type: this.t_(shape.type), id: shape.id || null};
switch (tmp.type) {
case 'CIRCLE':
tmp.radius = shape.getRadius();
tmp.geometry = this.p_(shape.getCenter());
break;
case 'MARKER':
tmp.geometry = this.p_(shape.getPosition());
break;
case 'RECTANGLE':
tmp.geometry = this.b_(shape.getBounds());
break;
case 'POLYLINE':
tmp.geometry = this.l_(shape.getPath(), encoded);
break;
case 'POLYGON':
tmp.geometry = this.m_(shape.getPaths(), encoded);
break;
}
shapes.push(tmp);
}
return shapes;
}
and the string formed to be parsed is:
[{"type":"CIRCLE","id":null,"radius":1730.4622192451884,"geometry":[32.3610810916614,50.91339111328125]},{"type":"CIRCLE","id":null,"radius":1831.5495077322266,"geometry":[32.35528086804335,50.997161865234375]},{"type":"CIRCLE","id":null,"radius":1612.2461023303567,"geometry":[32.34454947365649,51.011924743652344]}]

You can use Gson or Jackson for this. Create a POJO that hold the data and use these libs. An eg with Gson
import java.lang.reflect.Type;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
class JsonData {
private String type;
private String id;
private double radius;
private List<Double> geometry;
//Getters & Setters
}
public class JsonParser {
public static void main(String[] args) {
String json = "[{\"type\":\"CIRCLE\",\"id\":null,\"radius\":1730.4622192451884,\"geometry\":[32.3610810916614,50.91339111328125]},{\"type\":\"CIRCLE\",\"id\":null,\"radius\":1831.5495077322266,\"geometry\":[32.35528086804335,50.997161865234375]},{\"type\":\"CIRCLE\",\"id\":null,\"radius\":1612.2461023303567,\"geometry\":[32.34454947365649,51.011924743652344]}]";
Type listType = new TypeToken<List<JsonData>>() {}.getType();
List<JsonData> disputeSummaryArraylistobjectList = new Gson().fromJson(json, listType);
System.out.println(disputeSummaryArraylistobjectList);
}
}

You will need a JSON parser for Java like GSON or Jackson.
There are two strategies for parsing:
Creating Java objects and let the JSON parsers map elements in the input to fields
Iterating over the generic JSON data structure which the parser returns
The documentation of both projects contain lots of examples how to achieve either.

Related

How to put a JsonElement back into a JsonObject?

The goal is replace a value in a nested JSON.
Original JSON :
{
"data": {
"car": {
"xia": [
"a0.c904.b0"
]
}
}
}
Expected JSON:
{
"data": {
"car": {
"xia": [
"a0.c234.b0"
]
}
}
}
My code below gives me the JSONElement but I don't know how to put it back to the json object?
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
String inputJson = "{\n"
+ " \"data\": {\n"
+ " \"car\": {\n"
+ " \"xia\": [\n"
+ " \"a0.c904.b0\"\n"
+ " ]\n"
+ " }\n"
+ " }\n"
+ "}";
JsonObject jsonObject = new JsonParser().parse(inputJson).getAsJsonObject();
JsonElement jsonElement = jsonObject.get("data").getAsJsonObject().get("car").getAsJsonObject().get("xia");
String str = jsonElement.getAsString();
System.out.println(str);
String[] strs = str.split("\\.");
String replaced = strs[0] + "." + strs[1].replaceAll("\\d+", "234") + "." + strs[2];
System.out.println(replaced);
JsonElement jsonElementReplaced = new JsonParser().parse(replaced);
I just had to do :
jsonObject.get("data").getAsJsonObject().get("car").getAsJsonObject().add("xia", jsonElementReplaced);

How to retrieve a random element from a JSON array file in Java?

I have a two JSON files located in the resources package of my maven project. They are files called first-names.json and last-names.json. They both look something like this:
{
"first_names": [
"Aaron",
"Abby",
"Abigail",
etc..
]
}
My goal with this is I'm making an API that can retrieve a person with random attributes like first name and last name. Each one of these arrays has 10,000+ names. How would I go about retrieving a random element these files so I can assign it into my Person object?
Project Structure:
For reading file content from resources folder please refer to:
How do I load a file from resource folder?
What’s the best way to load a JSONObject from a json text file?
Assign file content to corresponding String variables.
Convert JSON string to JSON array then select a random item through names and last names array:
public static void main(String[] args) {
String namesJsonString = "{\n" +
" \"first_names\": [\n" +
" \"Aaron\",\n" +
" \"Abby\",\n" +
" \"Abigail\",\n" +
" ]\n" +
"}";
String lastNamesJsonString = "{\n" +
" \"last_names\": [\n" +
" \"last name 1\",\n" +
" \"last name 2\",\n" +
" \"last name 3\",\n" +
" ]\n" +
"}";
JSONObject namesJson = null;
JSONObject lastNamesJson = null;
try {
namesJson = new JSONObject(namesJsonString);
JSONArray namesJsonArray = namesJson.getJSONArray("first_names");
lastNamesJson = new JSONObject(lastNamesJsonString);
JSONArray lastNamesJsonArray = lastNamesJson.getJSONArray("last_names");
int namesArrayLength = namesJsonArray.length();
int lastNamesArrayLength = lastNamesJsonArray.length();
for (int i = 0; i < 5; i++) {
int randomNameIndex = (int) (Math.random() * namesArrayLength);
String randomName = namesJsonArray.getString(randomNameIndex);
int randomLastNameIndex = (int) (Math.random() * lastNamesArrayLength);
String randomLastName = lastNamesJsonArray.getString(randomLastNameIndex);
System.out.println(randomName + " " + randomLastName);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You can use this technique. Pass the file name as the argument to the app:
import javax.json.*;
import java.util.*;
import java.io.*;
public class JsonTest {
public static void main(String[] args) {
try (JsonReader in = Json.createReader(new FileReader(args[0]))) {
JsonArray array = in.readObject().getJsonArray("first_names");
int arrayLength = array.size();
Random r = new Random();
System.out.printf("Your random array element is %s%n", array.getString(r.nextInt(arrayLength)));
} catch (Throwable t) {
t.printStackTrace();
}
}
}

Return string in valid JSON

I want to return valid json string.
Ex:
{
"status":"Success",
"total_amt": "41",
"igst_amt": 14,
"sgst_amt": 0,
"cgst_amt": "12",
"cess_amt": 15
}
Expected:
{
"status":"Success",
"total_amt": "41",
"igst_amt": "14",
"sgst_amt": "0",
"cgst_amt": "12",
"cess_amt": "15"
}
I have wrote below code:
public String toString() {
return "{\"status\":\"" + status + "\",\"total_amt\":\"" + total_amt + "\",\"igst_amt\":\"" + igst_amt
+ "\",\"sgst_amt\":\"" + sgst_amt + "\",\"cgst_amt:\"" + cgst_amt + "\",\"cess_amt\":\"" + cess_amt + "\"}";
}
It is not returning valid JSON.
You can use a third party lib. This example uses GSON
class Result {
private String status;
#SerializedName("total_amt")
private int totalAmount;
#SerializedName("igst_amt")
private int igstAmount;
#SerializedName("sgst_amt")
private int sgstAmount;
#SerializedName("cgst_amt")
private int cgstAmount;
#SerializedName("cess_amt")
private int cessAmount;
public Result() {}
}
Result result = new Result();
// set your fields
String json = new Gson().toJson(result);
I hope igst_amt, sgst_amt and cess_amt are Integers.
So you add .toString() to them
public String toString() {
return "{\"status\":\"" + status + "\",\"total_amt\":\"" + total_amt + "\",\"igst_amt\":\"" + igst_amt.toString()
+ "\",\"sgst_amt\":\"" + sgst_amt.toString() + "\",\"cgst_amt:\"" + cgst_amt + "\",\"cess_amt\":\"" + cess_amt.toString() + "\"}";
}
Read about gson for returning json format. link to gson github
To simple use it you can:
final Gson gson = new GsonBuilder().setPrettyPrinting().create();
final String string = "you string";
return gson.toJson(string);

How can I parse GeoJson with Gson?

I want to write an app that will load GeoJson using Gson as the only dependency. Using Gson is pretty pedestrian but when it comes to the anonymous arrays for the coordinates I am at a loss. The 'coordinates' array is an array of arrays. AAARRRGGG!
"geometry":{
"type":"Polygon",
"coordinates":[
[
[
-69.899139,
12.452005
],
[
-69.895676,
12.423015
],
I can load all the other data but the 'coordinates' arrays do not have names, so how do I load them up?
I have tried several iterations of this but no joy...
public static final class Coordinate {
public final double[] coord;
public Coordinate(double[] coord) {
this.coord = coord;
}
}
Any help? I know there are already packages that parse geojson but I would like to understand the JSON loading. And what are unnamed arrays called? Anonymous arrays does not google well!
You can get Gson to parse triply-nested-nameless arrays by declaring the coordinate field as a double[][][].
Here's a runnable sample program that demonstrates how to do it:
import org.apache.commons.lang3.ArrayUtils;
import com.google.gson.Gson;
public class Scratch {
public static void main(String[] args) throws Exception {
String json = "{" +
" \"geometry\": {" +
" \"type\": \"Polygon\"," +
" \"coordinates\": [" +
" [" +
" [-69.899139," +
" 12.452005" +
" ]," +
" [-69.895676," +
" 12.423015" +
" ]" +
" ]" +
" ]" +
" }" +
"}";
Geometry g = new Gson().fromJson(json, Geometry.class);
System.out.println(g);
// Geometry [geometry=GeometryData [type=Polygon, coordinates={{{-69.899139,12.452005},{-69.895676,12.423015}}}]]
}
}
class Geometry {
GeometryData geometry;
#Override
public String toString() {
return "Geometry [geometry=" + geometry + "]";
}
}
class GeometryData {
String type;
double[][][] coordinates;
#Override
public String toString() {
return "GeometryData [type=" + type + ", coordinates=" + ArrayUtils.toString(coordinates) + "]";
}
}

Complex JSON deserialization with gson Java

How can I deserialize this complex JSON .
I want to access all objects and read.
For example SelectionId and AdditionalPriceInfo fields by indexing.
get(0).getSelectionId() --> d51d38c9-6e51-473c-b843-f24fef632f89
{
"Status": 0,
"Message": "",
"Result": {
"HasMore": "False",
"Itineraries": [
{
"SelectionId": "d51d38c9-6e51-473c-b843-f24fef632f89",
"AdditionalPriceInfo": null,
"Trips": [
{
"TotalTravelTime": "02:00:00"
}
]
},
{
"SelectionId": "ff44d76a-a4c8-4aff-9f9d-6db4e1f3092c",
"AdditionalPriceInfo": null,
"Trips": [
{
"TotalTravelTime": "01:23:00"
}
]
}
],
"SearchOriginCityText": "Long Beach",
"SearchOriginAirportCode": "LGB",
"SearchDestinationCityText": "SFO",
"SearchDestinationAirportCode": "SFO"
}
}
My code so far for accessing all I want:
Gson gson2 = new Gson();
AirJson airJson = gson2.fromJson(airFullResult3, AirJson.class);
Itineraries itineraries = gson2.fromJson(airFullResult3, Itineraries.class);
Result result = gson2.fromJson(airFullResult3, Result.class);
//Having null instead SFO
System.out.println(result.getSearchDestinationAirportCode());
//Having null
System.out.println(itineraries.getAdditionalPriceInfo());
When I split my JSON, I can access the values that I want.
{
"Itineraries": [{
"SelectionId": "d51d38c9-6e51-473c-b843-f24fef632f89",
"AdditionalPriceInfo": null
}, {
"SelectionId": "dda40b80-d8e4-4b76-9f78-83297b52afe9",
"AdditionalPriceInfo": null
}]
}
Successful code and I access values.
JsonParser parser = new JsonParser();
JsonObject rootObject = parser.parse(airFullResult).getAsJsonObject();
JsonElement projectElement = rootObject.get("Itineraries");
Type listofObject = new TypeToken<List<Itineraries>>(){}.getType();
List<Itineraries> itiList = gson2.fromJson(projectElement, listofObject);
//Having d51d38c9-6e51-473c-b843-f24fef632f89 as a result
//which is great
System.out.println(itiList.get(0).getSelectionId());
When I use the same code for first unallocated JSON, doesn't work and having java.lang.NullPointerException as error
you need to build one object with a couple of child objects which represents your json-structure. the following code works! (testet with java 8, and gson 2.6.2)
#Test
public void test() {
Gson gson = new Gson();
Data data = gson.fromJson(getJson(), Data.class);
Assert.assertNotNull(data);
Assert.assertNotNull(data.result);
Assert.assertNotNull(data.result.itineraries);
Assert.assertEquals(2, data.result.itineraries.length);
Assert.assertEquals("d51d38c9-6e51-473c-b843-f24fef632f89", data.result.itineraries[0].selectionId);
Assert.assertEquals("ff44d76a-a4c8-4aff-9f9d-6db4e1f3092c", data.result.itineraries[1].selectionId);
}
public class Data {
#SerializedName("Status")
int status;
#SerializedName("Message")
String message;
#SerializedName("Result")
Result result;
}
public class Result {
#SerializedName("HasMore")
String hasMore;
#SerializedName("Itineraries")
Itineraries[] itineraries;
#SerializedName("SearchOriginCityText")
String searchOriginCityText;
#SerializedName("SearchOriginAirportCode")
String searchOriginAirportCode;
#SerializedName("SearchDestinationCityText")
String searchDestinationCityText;
#SerializedName("SearchDestinationAirportCode")
String searchDestinationAirportCode;
}
public class Itineraries {
#SerializedName("SelectionId")
String selectionId;
#SerializedName("AdditionalPriceInfo")
String additionalPriceInfo;
#SerializedName("Trips")
Trips[] trips;
}
public class Trips {
#SerializedName("TotalTravelTime")
String totalTravelTime;
}
private String getJson() {
String json = "";
json += "{";
json += " \"Status\": 0,";
json += " \"Message\": \"\",";
json += " \"Result\": {";
json += " \"HasMore\": \"False\",";
json += " \"Itineraries\": [";
json += " {";
json += " \"SelectionId\": \"d51d38c9-6e51-473c-b843-f24fef632f89\",";
json += " \"AdditionalPriceInfo\": null,";
json += " \"Trips\": [";
json += " {";
json += " \"TotalTravelTime\": \"02:00:00\"";
json += " }";
json += " ]";
json += " },";
json += " {";
json += " \"SelectionId\": \"ff44d76a-a4c8-4aff-9f9d-6db4e1f3092c\",";
json += " \"AdditionalPriceInfo\": null,";
json += " \"Trips\": [";
json += " {";
json += " \"TotalTravelTime\": \"01:23:00\"";
json += " }";
json += " ]";
json += " }";
json += " ],";
json += " \"SearchOriginCityText\": \"Long Beach\",";
json += " \"SearchOriginAirportCode\": \"LGB\",";
json += " \"SearchDestinationCityText\": \"SFO\",";
json += " \"SearchDestinationAirportCode\": \"SFO\"";
json += " }";
json += "}";
return json;
}

Categories

Resources