I have a jsonElement as following
how can I retrieve "value2" with minimal amount of coding?
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Add jar in your project : org.json.
Suppose that you are having string,
String yourString = "{ \"key1\": \"value1\",\"key2\": \"value2\",\"key3\":\"value3\" }"
JSONObject jsonObj = new JSONObject(yourString);
First of all, check the desired key which you want to access to avoid nullPointer exception , then access you value . i.e.
Note: It is always a good practice to check whether this exists but in your case not mandatory
if(jsonObj.contains("key2") {
String key2 = jsonObj.getString("key2");
}
Related
Suppose I have a list of Map such as:
(Using json format just for demonstration)
List<Map> myList = [
{
"id": 12,
"name": "Harie"
},
{
"id": "Forty",
"location": "Earth"
},
{
"name": "Potah"
},
{
"id": "0"
}
]
Now I want all the "id" values in a single String object, separated by a separator.
For example, the above map should give me:
"12#Forty#0"
Note:
The order in which they are indexed in the list has to be maintained.
I know I can do it like this:
StringBuilder result = new StringBuilder();
for (Map map : myList) {
if (map.get("id") instanceof String) {
if(result.length()>0){
result.append('#');
}
result.append(map.get("id"));
}
}
//Use result.toString() for output
But I want a more readable and simplified code, preferably using Java stream api.
You can use stream and join all the key id values which are not null
String keyString = myList.stream()
.map(map->map.get("id"))
.filter(Objects::nonNull)
.map(Object::toString)
.collect(Collectors.joining("#"));
In case if you want to check if the value is String instance you can filter
filter(val-> val!=null && val instance String)
StringBuilder sb = new StringBuilder();
myList.stream().map((mapping) => {
sb.append(mapping.get(id))
sb.append("#")
}
You can add extra logic within the lambda function!
I am getting the response like this from Api. In which locationSector is fixed key but the inside key may exist or not and corresponding the key value as well.
this is json string.
How can I store this in hashmap also the inner value can also be stored in hash map like.
HashMap<String, HashMap<String,List<String>>>
"locationSector": {
"Adampur": [
"Adampur",
"Agroha",
"Anaj Mandi",
"Auto Market",
"Bhadu Colony",
"Chulibagrian"
],
"Allahabad": [
"Allahabad"
],
"Gurgaon":[
"Dlf 1",
"Dlf 2"
]
}
try this out if you're using org.json library:
import com.fasterxml.jackson.databind.ObjectMapper;
Map<String, Object> response = new ObjectMapper().readValue(str, HashMap.class);
str = youre json String.
Simple as this, if you want a studentId,
String studentIds = response.get("student id").toString();
We are trying to parse an json object which is having different key-values everytime.
{
"Key1": "Val1",
"Key2": "Val2",
"Key3": "Val3",
"Key4": "Val4",
"Key5": "Val5",
.........,
.........,
"KeyN": "ValN"
}
Here "KeyN" can have different names also "ValueN" also will be different.
It is very clear that this will not parse in one go, like :
ObjectX objetX = new Gson().fromJson(sourceJson, ObjectX.class);
How should we parse this ? even if we choose to parse manually ? We trying this in android Volley response.
Using Gson java library parse your json object into HashMap<String,String>.
sample code
sourceJson = {
"Key1": "Val1",
"Key2": "Val2",
"Key3": "Val3",
"Key4": "Val4",
"Key5": "Val5",
.........,
.........,
"KeyN": "ValN"
};
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(sourceJson, type);
If you want more generic solution should be
Map map = gson.fromJson(sourceJson, Map.class);
So this is my sample Json Text,
{
"Date": [
1545,
"20 January 2014"
],
"docText": "ABCD",
"docSource": "",
"docID": 99,
"docDate": "",
"Date": [
1930,
"1995/11",
"past decade",
"today",
"Today"
],
"docText": "JJJJJJJ\"",
"Organization": [
"x",
"y",
"z"
],
"docSource": "",
"docID": 98,
"docDate": "",
"Person": "xxxxxx"
}
Now I need a Java code to Read from this file and Display all the docText, docID Entities. I'm able to retrieve only one Entity.
This is the part of the code im using.
JSONParser jsonParser = new JSONParser();
try {
FileReader fileReader = new FileReader(jsonFilePath);
JSONObject jsonObject = (JSONObject) jsonParser.parse(fileReader);
String docid = (String) jsonObject.get("docText");
System.out.println("DocText: " +docid);
long members = (long) jsonObject.get("docID");
System.out.println("docID: " + members);
JSONArray names = (JSONArray) jsonObject.get("Organization");
Iterator i = names.iterator();
while (i.hasNext()) {
System.out.println("Organization: "+i.next());
I really need this working soon! Thank you
The JSON file has duplicate keys so you probably can't read them all using a standard parser.
From http://www.ietf.org/rfc/rfc4627.txt:
An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.
Instead, I'd expect each entity to be a separate object within an array.
AFAIK there is no option to fetch multiple values from a JSON object in a single get...
{
"Employee": [
{
"empMID": "mock:1",
"comments": [],
"col1": "something",
"contact": [{"address":"2400 waterview", "freetext":true}
],
"gender": "male"
},
{
"empMID": "mock:2",
"comments": [],
"col1": "something",
"contact": [{"address":"2200 waterview", "freetext":true}
],
"gender": "female"
}
],
"cola": false,
"colb": false
}
This is how my Json file looks .I m required to convert this json to a csv .(I m trying to convert a multi-dimesional data to 2d).I m using gson for my purpose.I cannot use gson.fromgson() function to object map with a template because it should be generic .
I know we can use CDL to convert jsonarray to csv format but It wont work in my case .
my csv format looks like
Employee*
empMID,comment.$,contact.address,contact.freetext,gender
mock:1,,2400 waterview,TRUE,male
mock:123,,2200 waterview,TRUE,female
colA#
TRUE
colB#
FALSE
I tried using google-GSON api to convert to this format .But I m not able to convert to this format .I have used * to represent its a json array and # to represent its a primitive type and contact.address to represent nested array inside another json array .I having problem relating this nested structure .I m able to traverse everything recursively like a column. Thanks in advance
public static void main(String[] args) throws IOException{
BufferedReader reader=null;
StringBuilder content=null;
String result=null;
reader = new BufferedReader(new FileReader("temp.json"));
String line = null;
content= new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
result= content.toString();
JsonElement jelement = new JsonParser().parse(result);
printJsonRecursive(jelement);
}
public static void printJsonRecursive(JsonElement jelement){
if(jelement.isJsonPrimitive()){
System.out.println(jelement.getAsString());
return;
}
if(jelement.isJsonArray()){
JsonArray jarray= jelement.getAsJsonArray();
for(int i=0;i<jarray.size();i++){
JsonElement element= jarray.get(i);
printJsonRecursive(element);
}
return;
}
JsonObject jobject= jelement.getAsJsonObject();
Set<Entry<String, JsonElement>> set= jobject.entrySet();
for (Entry<String, JsonElement> s : set) {
printJsonRecursive(s.getValue());
}
}
}
You can achieve this thru reflection if you have a object mapped to the json.
use gson/jackson to convert json to java object
append fields using reflection by iterating the class and get any field you interested in.
append value with reflection by getting value from the target object.
More detail look at my blog post below:
vcfvct.wordpress.com/2015/06/30/converting-nested-json-files-to-csv-in-java-with-reflection/
You are not printing the key. This should fix it.
for (Entry<String, JsonElement> s : set) {
System.out.println(s.getKey()); //Added
printJsonRecursive(s.getValue());
}
You can take care of \ns from here.
EDIT
If you want to print the keys just once for repeating json objects, create a Java bean to hold the data and populate it during your recursion. Once the bean is complete, add a method there to print all the data in the format you want (printing keys only once and so on).
You can use the library json2flat for converting your JSON to CSV.
This library doesn't require any POJO's. It simply takes your JSON as string and returns a 2D representation of it in the format of List<Object[]>.
For example for the JSON:
{
"Employee": [
{
"empMID": "mock:1",
"comments": [],
"col1": "something",
"contact": [{"address":"2400 waterview", "freetext":true}
],
"gender": "male"
},
{
"empMID": "mock:2",
"comments": [],
"col1": "something",
"contact": [{"address":"2200 waterview", "freetext":true}
],
"gender": "female"
}
],
"cola": false,
"colb": false
}
It gives an output:
/cola,/colb,/Employee/empMID,/Employee/col1,/Employee/gender,/Employee/contact/address,/Employee/contact/freetext
,,"mock:1","something",,"2400 waterview",true
,,"mock:2","something",,"2200 waterview",true
false,false,,,,,
/**
* Get separated comlumns used a separator (comma, semi column, tab).
*
* #param headers The CSV headers
* #param map Map of key-value pairs contains the header and the value
*
* #return a string composed of columns separated by a specific separator.
*/
private static String getSeperatedColumns(Set<String> headers, Map<String, String> map, String separator) {
List<String> items = new ArrayList<String>();
for (String header : headers) {
String value = map.get(header) == null ? "" : map.get(header).replaceAll("[\\,\\;\\r\\n\\t\\s]+", " ");
items.add(value);
}
return StringUtils.join(items.toArray(), separator);
}