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);
Related
I'm using Java.
I have a JSON string like this given below :
{
"4562": {
"a": "foo1",
"b": "56",
"c": "1342"
},
"4563": {
"a": "foo2",
"b": "57",
"c": "1343"
}
}
I want to store all the data from the JSON string into Map.
How to do that ?
You need to use Jackson Library (jackson-databind).
Code :
import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Example {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
String inputJson = "{ \n" +
" \"4562\": { \n" +
" \"a\": \"foo1\", \n" +
" \"b\": \"56\", \n" +
" \"c\": \"1342\" \n" +
" },\n" +
" \"4563\": { \n" +
" \"a\": \"foo2\", \n" +
" \"b\": \"57\", \n" +
" \"c\": \"1343\" \n" +
" }\n" +
"}";
Map<String, Map<String, String>> map = mapper.readValue(inputJson, Map.class);
System.out.println(map);
}
}
Output :
{4562={a=foo1, b=56, c=1342}, 4563={a=foo2, b=57, c=1343}}
Download jar from here : https://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-databind/2.10.1/
Use Gson:
String json = ...;
Gson gson = new GsonBuilder.setPrettyPrinting().create();
Map<String, Map<String, String>> map = gson.<Map<String, Map<String, String>>>fromJson(json, Map.class);
System.out.println(map);
I am trying to get specific value from json file. Here is my json file.
{
"books": ["book1","book2","book3","book4"],
"set_with_ratio": {
"tweaks_es": "7",
"ratio": {
"brand_defined_sets_ratio": {
"default": {
"desktop": {
"16": "85",
"11": "95",
"19": "10",
"12": {
"2": "50"
}
}
},
"rentals": {
"desktop": {
"16": "75",
"11": "45",
"12": {
"2": "10"
}
}
}
}
}
}
}
How can I get books array elements one by one? I tried this.
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonData);
JSONArray jsonArray = (JSONArray) jsonObject.get("books");
//Iterating the images of the array
Iterator<Object> iterator = jsonArray.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
From this I got this error java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.JSONArray
how can I get data for x.set_with_ratio.ratio.brand_defined_sets_ratio.default.desktop.11 this json path. I am trying this code in Java.
JSONParser jsonParser = new JSONParser();
try {
//Parsing the contents of the JSON file
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("sample.json"));
String id = jsonObject.get("set_with_ratio").toString();
System.out.println(id);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
Here I get the total json file but cannot manage to get expected result.
Try this
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.junit.Test;
public class JavaTest {
#Test
public void name() {
JSONParser jsonParser = new JSONParser();
try {
//Parsing the contents of the JSON file
JSONObject jsonObject = (JSONObject) jsonParser.parse("{\n" +
" \"set_with_ratio\": {\n" +
" \"tweaks_es\": \"7\",\n" +
" \"ratio\": {\n" +
" \"brand_defined_sets_ratio\": {\n" +
" \"default\": {\n" +
" \"desktop\": {\n" +
" \"16\": \"85\",\n" +
" \"11\": \"95\",\n" +
" \"19\": \"10\",\n" +
" \"12\": {\n" +
" \"2\": \"50\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"rentals\": {\n" +
" \"desktop\": {\n" +
" \"16\": \"75\",\n" +
" \"11\": \"45\",\n" +
" \"12\": {\n" +
" \"2\": \"10\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}");
String id = ((JSONObject) ((JSONObject) ((JSONObject) ((JSONObject) ((JSONObject) jsonObject.get("set_with_ratio"))
.get("ratio"))
.get("brand_defined_sets_ratio"))
.get("default"))
.get("desktop"))
.get("11" +
"").toString();
System.out.println(id);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Result is 95
Try this :
JSONTokener parser = new JSONTokener(new FileReader("sample.json"));
JSONObject jsonObject = new JSONObject(parser);
String id = jsonObject.getJSONObject("set_with_ratio").getJSONObject("ratio").getJSONObject("brand_defined_sets_ratio").getJSONObject("default").getJSONObject("desktop").getString("11");
Library used : org.json
I am trying to add specific values from the following JSON to a Java ArrayList. I would then like to use this ArrayList within a JSP. This is the JSON:
{
"page": 1,
"rpp": 3,
"total": 3294,
"request_time": "2018-04-23T16:10:20+01:00",
"stops": [
{
"atcocode": "370023715",
"longitude": -1.46616,
"latitude": 53.38248,
"distance": 57
},
{
"atcocode": "370027281",
"longitude": -1.46583,
"latitude": 53.38228,
"distance": 77
},
{
"atcocode": "370022803",
"longitude": -1.46616,
"latitude": 53.38227,
"distance": 80
}
]
}
I would like to add each longitude and latitude elements from under the "stops" subtree into 2 different ArrayLists. This is my attempted code for that:
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
try {
String json = readUrl (link);
JsonParser parser = new JsonParser();
JsonElement element = parser . parse (json);
if (element.isJsonObject()) {
JsonObject bus = element . getAsJsonObject ();
JsonArray array = bus . getAsJsonArray ("stops");
for (int i = 0; i < array.size(); i++) {
List<String> longitudes = new ArrayList<String>();
List<String> latitudes = new ArrayList<String>();
longitudes.add(array.get(i)).get("longitude");
latitudes.add(array.get(i)).get("latitude");
request.setAttribute("longitudes", longitudes);
request.setAttribute("latitudes", latitudes);
RequestDispatcher dispatcher = request . getRequestDispatcher ("latlong.jsp");
dispatcher.forward(request, response);
}
}
}
}
i get the following error of: "error: incompatible types: JsonElement cannot be converted to String"
Thank you in advance!
One other error you have is that the longitudes, latitudes lists are inside of the loop.
Here is a simple testable piece of code which extracts the data from the JSON and can be tested locally. You can adapt it to your purposes ...
public static void main(String[] args) {
String json = "{\n" +
"\"page\": 1,\n" +
"\"rpp\": 3,\n" +
"\"total\": 3294,\n" +
"\"request_time\": \"2018-04-23T16:10:20+01:00\",\n" +
"\"stops\": [\n" +
"{\n" +
" \"atcocode\": \"370023715\",\n" +
" \"longitude\": -1.46616,\n" +
" \"latitude\": 53.38248,\n" +
" \"distance\": 57\n" +
"},\n" +
"{\n" +
" \"atcocode\": \"370027281\", \n" +
" \"longitude\": -1.46583,\n" +
" \"latitude\": 53.38228,\n" +
" \"distance\": 77\n" +
"},\n" +
"{\n" +
" \"atcocode\": \"370022803\",\n" +
" \"longitude\": -1.46616,\n" +
" \"latitude\": 53.38227,\n" +
" \"distance\": 80\n" +
" }\n" +
"]\n" +
"}";
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(json);
List<String> longitudes = new ArrayList<>();
List<String> latitudes = new ArrayList<>();
if (element.isJsonObject()) {
JsonObject bus = element . getAsJsonObject ();
JsonArray array = bus.getAsJsonArray("stops");
array.forEach(jsonElement -> {
extractToList(longitudes, (JsonObject) jsonElement, "longitude");
extractToList(latitudes, (JsonObject) jsonElement, "latitude");
});
}
System.out.println(longitudes);
System.out.println(latitudes);
}
private static void extractToList(List<String> list, JsonObject jsonElement, String field) {
final JsonElement longitude = jsonElement.get(field);
if(longitude != null) {
list.add(longitude.getAsString());
}
}
If you run this you get printed out on the console:
[-1.46616, -1.46583, -1.46616]
[53.38248, 53.38228, 53.38227]
I have assumed you are using Google's GSON library.
Instead of
longitudes.add(array.get(i)).get("longitude");
latitudes.add(array.get(i)).get("latitude");
Use
longitudes.add(array.get(i).get("longitude").getAsString());
latitudes.add(array.get(i).get("latitude").getAsString());
Given the following JSON response:
{
"status": "OK",
"regions": [
{
"id": "69",
"name": "North Carolina Coast",
"color": "#01162c",
"hasResorts": 1
},
{
"id": "242",
"name": "North Carolina Inland",
"color": "#01162c",
"hasResorts": 0
},
{
"id": "17",
"name": "North Carolina Mountains",
"color": "#01162c",
"hasResorts": 1
},
{
"id": "126",
"name": "Outer Banks",
"color": "#01162c",
"hasResorts": 1
}
]
}
I'm trying to create a List of Region objects. Here's a very abridged version of my current code:
JSONObject jsonObject = new JSONObject(response);
String regionsString = jsonObject.getString("regions");
Type listType = new TypeToken<ArrayList<Region>>() {}.getType();
List<Region> regions = new Gson().fromJson(regionsString, listType);
This is all working fine. However, I'd like to exclude the regions in the final List that hasResorts == 0. I realize I can loop through the actual JSONObjects and check them before calling fromJSON on each region. But I'm assuming there is a GSON specific way of doing this.
I was looking at the ExclusionStrategy(). Is there a simple way to implement this to JSON deserialization?
ExclusionStrategy won't help you since it works without the context of deserialization. Indeed, you can exclude only a specific kind of class. I think that best way of doing it is through custom deserialization. Here is what I mean (you can copy&paste&try immediately):
package stackoverflow.questions.q19912055;
import java.lang.reflect.Type;
import java.util.*;
import stackoverflow.questions.q17853533.*;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
public class Q19912055 {
class Region {
String id;
String name;
String color;
Integer hasResorts;
#Override
public String toString() {
return "Region [id=" + id + ", name=" + name + ", color=" + color
+ ", hasResorts=" + hasResorts + "]";
}
}
static class RegionDeserializer implements JsonDeserializer<List<Region>> {
public List<Region> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
if (json == null)
return null;
ArrayList<Region> al = new ArrayList<Region>();
for (JsonElement e : json.getAsJsonArray()) {
boolean deserialize = e.getAsJsonObject().get("hasResorts")
.getAsInt() > 0;
if (deserialize)
al.add((Region) context.deserialize(e, Region.class));
}
return al;
}
}
/**
* #param args
*/
public static void main(String[] args) {
String json =
" [ "+
" { "+
" \"id\": \"69\", "+
" \"name\": \"North Carolina Coast\", "+
" \"color\": \"#01162c\", "+
" \"hasResorts\": 1 "+
" }, "+
" { "+
" \"id\": \"242\", "+
" \"name\": \"North Carolina Inland\", "+
" \"color\": \"#01162c\", "+
" \"hasResorts\": 0 "+
" }, "+
" { "+
" \"id\": \"17\", "+
" \"name\": \"North Carolina Mountains\", "+
" \"color\": \"#01162c\", "+
" \"hasResorts\": 1 "+
" }, "+
" { "+
" \"id\": \"126\", "+
" \"name\": \"Outer Banks\", "+
" \"color\": \"#01162c\", "+
" \"hasResorts\": 1 "+
" } "+
" ] ";
Type listType = new TypeToken<ArrayList<Region>>() {}.getType();
List<Region> allRegions = new Gson().fromJson(json, listType);
System.out.println(allRegions);
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(listType, new RegionDeserializer());
Gson gson2 = builder.create();
List<Region> regionsHaveResort = gson2.fromJson(json, listType);
System.out.println(regionsHaveResort);
}
}
HOw would I go about parsing JSON using the google GSON library? An example of my returned JSON is:
[
{
"title": "Down",
"album": "Down",
"length": 212.61,
"artist": "Jay Sean"
},
{
"title": "Come to Me (Peace)",
"album": "Growing Pains",
"length": 301.844,
"artist": "Mary J Blige"
}
]
This is an array of json objects, is that right? How would I go about extracting this with Gson? This is what im trying but am getting null pointer exceptions:
JsonElement jelement = new JsonParser().parse(jsonInfo);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("");
JsonArray jarray = jobject.getAsJsonArray("");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("title").toString();
You must create a Type instance for List.
class MyObj {
String title;
String album;
double length;
String artist;
}
String json = "[\n" +
" {\n" +
" \"title\": \"Down\",\n" +
" \"album\": \"Down\",\n" +
" \"length\": 212.61,\n" +
" \"artist\": \"Jay Sean\"\n" +
" },\n" +
" {\n" +
" \"title\": \"Come to Me (Peace)\",\n" +
" \"album\": \"Growing Pains\",\n" +
" \"length\": 301.844,\n" +
" \"artist\": \"Mary J Blige\"\n" +
" }\n" +
"]";
Type listType = new TypeToken<List<MyObj>>() {}.getType();
List<MyObj> list = new Gson().fromJson(json, listType);
System.out.println(new Gson().toJson(list));
Gson gson = new Gson();
gson. //a lot methods