I am very new to Java but have figured out how to extract values from a json file - but I can not understand how to change the value.
JsonElement staff = gson.fromJson(new FileReader("file1.json"), JsonElement.class);
String json = gson.toJson(staff);
JsonParser parser = new JsonParser();
JsonElement jsonTree = parser.parse(json);
JsonObject jsonObject = jsonTree.getAsJsonObject();
JsonElement f3obj = ((JsonObject) ((JsonObject) ((JsonArray) jsonObject.get("Options")).get(1)).get("Option").get("Dialog");
How can I update the value of "Dialog" in this object?
You can update using below mentioned code.
JsonObject f3obj = ((JsonArray) jsonObject.get("Options")).get(1).getAsJsonObject().get("Option").getAsJsonObject();
f3obj.addProperty("Dialog", new Integer(10));
System.out.println(f3obj);
I am using Guava library so below mentioned packages are being used.
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
You can create new Json from the given response values.
def jsonData = new JsonSlurper().parseText(response.contentAsString)
And you can use the JSONObject as follows:
JSONObject newStudent = jsonData.getJSONObject("student");
newStudent.put("name", "John");
If you get an Array as a response use the following code:
JSONObject newStudent = jsonData.getJSONObject(0).getJSONObject("student");
nweStudent.put("name", "John");
For building JSON using a builder you can use the Json builder:
def builder = new JsonBuilder()
builder([
[type: 'string', values: ['no', 'name', 'here']]
])
Related
I have a json object like below
String jsonStr ="{\"m\":{\"p\":{\"0\":{\"ms\":{\"s\":1}}}}}";
From this I want to get the value of key s
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
JSONObject object = new JSONObject(jsonStr);
System.out.println(object.get("m"));
JSONObject mObj = (JSONObject) object.get("m");
JSONObject pObj = (JSONObject) mObj.get("p");
JSONObject oObj = (JSONObject) pObj.get("0");
JSONObject sObj = (JSONObject) oObj.get("ms");
System.out.println(sObj.get("s"));
Instead of using the above logic is there any ways to easily get the value of key s
Creating an object that represents the JSON would be a much cleaner approach. However, for dynamic keys recursion could be used.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
String jsonStr = "{\"m\":{\"p\":{\"0\":{\"ms\":{\"s\":1}}}}}";
Gson gson = new GsonBuilder().create();
Map data = gson.fromJson(jsonStr, Map.class);
Object value = obj.get(data, "s");
System.out.println(value); //1.0
//Input JSON as Map & key to search on
public Object get(Map data, String key) {
System.out.println(data);
if (!data.containsKey(key)) {
for (Object v : data.values()) {
return get((Map) v, key);
}
}
return data.get(key);
}
I have simple json which looks like this :
[
{
"id":"0",
"name":"Bob",
"place":"Colorado",
},
{
"id":"1",
"name":"John",
"place":"Chicago",
},
{
"id":"2",
"name":"Marry",
"place":"Miami",
}
]
What I want is using Java to create list of strings (List<String>) that contains all 'names'. I have some experience using Gson and I think about something like:
Gson gson = new Gson();
String[] stringArray= gson.fromJson(jsonString, " ".class);
The problem with this method is that I should create some POJO class which I didn`t in this case. Is it any way I can achieve it without creating separate class with this 'name' property ?
Using Jackson to parse, and Java 8 Streams API for extracting only the name field; the following may help you:
// Your string
jsonString = "[{ \"id\":\"0\", \"name\":\"Bob\", \"place\":\"Colorado\" }, { \"id\":\"1\", \"name\":\"John\", \"place\":\"Chicago\"}, { \"id\":\"2\", \"name\":\"Marry\", \"place\":\"Miami\" }]";
// using Jackson to parse
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.getTypeFactory();
List<MyInfo> myObjectList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, MyInfo.class));
// Java 8 Collections
List<String> nameList = myObjectList.stream().map(MyInfo::getName).collect(Collectors.toList());
Beware, it implies the usage of a MyInfo class representing your a Java class in which Json objects of yours would fit in.
You can use JSONArray to get value from key 'name'. Like this:
JSONArray jSONArray = new JSONArray(yourJson);
List<String> list = new ArrayList<>();
for (int i = 0; i < jSONArray.length(); i++) {
JSONObject object = (JSONObject) jSONArray.get(i);
String value = object.getString("name");
System.out.println(value);
list.add(value);
}
You may try the following code snippet,
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
List<String> ls = new ArrayList<String>();
JSONObject jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
JSONParser jsonParse = new JSONParser();
String str = "[{\"id\": \"0\",\"name\": \"Bob\",\"place\": \"Colorado\"},"
+ "{\"id\": \"1\",\"name\": \"John\",\"place\": \"Chicago\"},"
+ "{\"id\": \"2\",\"name\": \"Marry\",\"place\": \"Miami\"}]";
try {
jsonArr= (JSONArray) jsonParse.parse(str); //parsing the JSONArray
if(jsonArr!=null){
int arrayLength =jsonArr.size(); //size is 3 here
for(int i=0;i<arrayLength;i++){
jsonObj = (JSONObject) jsonParse.parse(jsonArr.get(i).toString());
ls.add(jsonObj.get("name").toString()); //as we need only value of name into the list
}
System.out.println(ls);
}
} catch (ParseException e) {
e.printStackTrace();
}catch(Exception e1){
e1.printStackTrace();
}
As you have array, use JSONArray and used jsonParse to avoid any parsing error.
I have used json-simple API to acheive the above.
Is there a way to just one field from the JSON string? My code is as follows:
Object obj = parser.parse(resp);
System.out.println(obj);
JSONArray array = new JSONArray();
array.add(obj);
JSONObject obj2 = (JSONObject)array.get(0); //Getting NPE here
//Object obj3 = obj2.get("data");
System.out.println("Data: " + obj2.get("data"));
//System.out.println("Email: " + obj3.get("email_address"));
I'm using the following libraries
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
From the response string resp, I just need data.email_address. I am unable to find a way to do it.
So if this is your input:
{
"data": {
"email_address": "example#example.com"
}
}
You first will need to make it a JSONObject:
JSONObject object = (JSONObject) new JSONParser().parse(json);
And then you can get data, another JSONObject:
JSONObject data = (JSONObject) object.get("data")
And from your data Object you can get email_address:
String email = data.get("email_address").toString();
If your input is an array of users, like this:
{
"users": [
{
"data": {
"email_address": "example#example.com"
}
},
{
"data": {
"email_address": "exapmle2#example2.com"
}
}
]
}
You can get it the same way:
JSONObject object = (JSONObject) new JSONParser().parse(json);
JSONArray users = (JSONArray) object.get("users");
JSONObject user0 = (JSONObject) users.get(0);
JSONObject user0data = (JSONObject) user0.get("data");
String email = user0data.get("email_address").toString();
First parse the whole JSON into an Object. Then get an array called users, from that array, get index 0. From that Object, get data, and then email_address
The other option is to use jsonpath.
Using the same Json blob as Lorant:
{
"data": {
"email_address": "example#example.com"
}
}
You would use the following expression.
$.data.email_address
Or if it was an array, simply.
$.users.[data].email_address
An online tool can be used to experiment and learn the syntax, but if you know xpath it should be somewhat familiar already.
import org.json.JSONObject;
JSONObject json = new JSONObject(record);
json.getString("fieldName"));
I want to read a string as a JSON format(it doesn't have to be JSON, but it seems like JSON format) and represent it to a hashMap(key : Keyword, value : COUNT)
for example, assume I have a String.
String s ={"Welcome":1,"Hi":2,"Hello":1,"Jin":1};
Then, make it classification.(for Hashmap key --> word, value--> number). final result would be something like as below.
HashMap<String,String> result;
result.get("Jin"); // output : 1
result.get("Hi"); // output : 2
but my codes, it doesn't go with right way.
JSONParser parser = new JSONParser();
Object obj = parser.parse(s);
JSONArray array = new JSONArray();
array.add(obj);
System.out.println(array.get(0)); //output: {"Welcome":1,"Hi":2,"Hello":1,"Jin":1}
can it be possible with JSON? or should I split them one by one? (such as split them with "," first and ":" ... so on)
Please give me your kind advice.
Try with below code snippet.
public static void main(final String[] args) throws ParseException {
String s = "{\"Welcome\":1,\"Hi\":2,\"Hello\":1,\"Jin\":1}";
JSONParser parser = new JSONParser();
HashMap<String, Long> obj = (HashMap<String, Long>) parser.parse(s);
for(String key : obj.keySet()) {
System.out.println("Key:" + key + " value:" + obj.get(key));
}
}
You can use org.json to fulfill your requirement.
E.g.
String s = "{\"Welcome\":1,\"Hi\":2,\"Hello\":1,\"Jin\":1}";
JSONObject result = new JSONObject(s);
System.out.println(result.get("Jin")); // output : 1
System.out.println(result.get("Hi")); // output : 2
The easiest to achieve this is by using JACKSON parsers.
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
String s = "{\"Welcome\":1,\"Hi\":2,\"Hello\":1,\"Jin\":1}";
ObjectMapper mapper = new ObjectMapper();
Map<String, String> map = mapper.readValue(s, new TypeReference<HashMap<String, String>>() {
});
map.forEach((k, v) -> System.out.println("Key is " + k + " value is " + v));
Prints :
Key is Hi value is 2
Key is Hello value is 1
Key is Welcome value is 1
Key is Jin value is 1
Its a json object not an array...
try this one :
JSONObject jsonObj = new JSONObject(jsonString.toString());
Use Google JSON i.e gson library(2.6.2) and your problem will be solved.
Please have a look to the following code
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class StackOverFlowQuestionset {
public static void main(String[] args) {
String s ="{\"Welcome\":1,\"Hi\":2,\"Hello\":1,\"Jin\":1}";
HashMap<String,String> result=new HashMap<String,String>();
Gson gson = new Gson();
JsonElement jsonElement = gson.fromJson(s, JsonElement.class);
JsonObject jsonObject = jsonElement.getAsJsonObject();
Set<Entry<String, JsonElement>> jsonEntrySet = jsonObject.entrySet();
for(Entry<String, JsonElement> entry:jsonEntrySet){
result.put(entry.getKey(), entry.getValue().toString());
}
System.out.println(result.get("Jin"));
System.out.println(result.get("Welcome"));
System.out.println(result.get("Hi"));
}
}
I'm using GSON for parsing JSON response.
Unfortunately the WebApi on the server has quite untypical JSON objects.
I need to parse Attachments array from this JSON (there can be more attachments):
{"htmlMessage":"text","Attachments":{"8216096_0":{"content":null,"filename":"plk.jpg","contentType":"image/jpeg","contentDisposition":"attachment","size":86070}}}
Where 8216096_0 is attachments id.
I can't do it with Gson (or I don't know how) so I'm trying to do it with JSONObjects:
// parse attachments
JSONObject attachmentsJson = result.getJSONObject("Attachments");
Then I have one JSONObject with an array of attachments, but I don't know how to get them to the ArrayList from JSONObject because the key value isn't static but generated id..
Thank you
//EDIT:
Thanks to all guys for helping! My final solution looks like this especially thanks to #Jessie A. Morris and his final answer!
List<AttachmentModel> attachmentsList = new ArrayList<AttachmentModel>();
for( Map.Entry<String, JsonElement> attachment : attachments.entrySet()) {
AttachmentModel attachmentModel = new AttachmentModel();
attachmentModel = gson.fromJson(attachment.getValue().getAsJsonObject().toString(), AttachmentModel.class);;
attachmentModel.setmUid(attachment.getKey());
attachmentsList.add(attachmentModel);
}
Okay, I've changed my example a little bit and am certain that this does work correctly (I just tested it):
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by jessie on 14-07-09.
*/
public class TestGson {
private static String JSON = "{\"htmlMessage\":\"text\",\"Attachments\":{\"8216096_0\":{\"content\":null,\"filename\":\"plk.jpg\",\"contentType\":\"image/jpeg\",\"contentDisposition\":\"attachment\",\"size\":86070}}}\n";
public static void main(String[] args) {
JsonObject json = new JsonParser().parse(JSON).getAsJsonObject();
JsonObject attachments = json.getAsJsonObject("Attachments");
List<JsonObject> attachmentsList = new ArrayList<JsonObject>();
for( Map.Entry<String, JsonElement> attachment : attachments.entrySet()) {
attachmentsList.add(attachment.getValue().getAsJsonObject());
}
System.out.println("attachmentsList at the end? " + attachmentsList);
}
}
I'm not completely sure if this really works:
final Map<String,JSONObject> attachmentsJson = (Map<String,JSONObject>) jsonArray.getJSONObject("Attachments");
for(String attachmentId : attachmentsJson.keySet()) {
final JSONObject attachmentJson = attachmentsJson.get(attachmentId);
}
The "Attachments" obj in your example is not an array.
Json arrays are denoted by [....].
"Attachments" is a Json object holding an inner object called "8216096_0".
so to get the inner values do as follows:
JSONObject attachmentsJson = result.getJSONObject("Attachments");
JSONObject inner = attachmentsJson.getJSONObject("8216096_0");
// and interrogate the inner obj:
String content = inner.getString("content");
String filename = inner.getString("filename");
Finally, and for example sake, I will add the code for processing a (real) Json array:
{"htmlMessage":"text",
"Attachments":[{"8216096_0":{"content":null,"filename":"plk.jpg","contentType":"image/jpeg",
"contentDisposition":"attachment","size":86070}},
{"8216096_1":{"content":null,"filename":"plk.jpg","contentType":"image/jpeg",
"contentDisposition":"attachment","size":86070}},
]
}
It will go like this:
JSONArray attachmentsJson = result.getJSONObject("Attachments");
int len = attachmentsJson.length();
for (int i = 0; i < len; i++) {
JSONObject elem = attachmentsJson.getJSONObject(i); // <------ get array element
JSONObject inner = elem.getJSONObject("8216096_0");
// and interrogate the inner obj:
String content = inner.getString("content");
String filename = inner.getString("filename");
}
..Or similar, depending on your Json's exact format.