Nested JSON parsing - java

I have the following JSON string
String JSON = {"IP":{"string":"1.2.3.4"},"UrlParameters":{"map":{"pw":"36","mu":"www.abc.com"}}}
I need to get the value of pw and mu in Java. How do I parse it?

You may try this:
public static void main(String[] args) throws JSONException{
// TODO Auto-generated method stub
String JSON = "{\"IP\":{\"string\":\"1.2.3.4\"},\"UrlParameters\":{\"map\":{\"pw\":\"36\",\"mu\":\"www.abc.com\"}}}";
JSONObject jsonObject = new JSONObject(JSON);
System.out.println("Full JSON String: "+jsonObject);
JSONObject urlParametersMap = jsonObject.getJSONObject("UrlParameters").getJSONObject("map");
System.out.println("mu: "+urlParametersMap.getString("mu"));
System.out.println("pw: "+urlParametersMap.getString("pw"));
}

Related

How can I create a new element/node and then add a new key and value to it?

I have the following code:
import org.json.JSONObject;
import org.json.XML;
public class Xml2Json {
public static void main(String[] args) {
String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
jsonObject.getJSONObject("users").getJSONObject("user").remove("age");
jsonObject.getJSONObject("users").append("marks",23); }
}
it produces the output shown below:
{"users":{"report":{"sub":"eng","score":30},"marks":[23],"user":{"name":"test1"}}}
But I need to add a new element newUser to users and the marks should be inside the newUser, just like:
{"users":{"report":{"sub":"eng","score":30},"newUser":{"marks":{23}},"user":{"name":"test1"}}}
Could anyone help me?
Instead of your code use below mentioned code:
public static void main(String[] args) throws JSONException {
String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
jsonObject.getJSONObject("users").getJSONObject("user").remove("age");
Map<String, int[]> marks = new HashMap<>();
marks.put("marks", new int[]{23});
jsonObject.getJSONObject("users").put("newUser", marks);
System.out.println(jsonObject);
}
where line jsonObject.getJSONObject("users").put("newUser", marks); will add new key(newUser) with corresponding mapping marks as Map object.
Without Map and HashMap:
public static void main(String[] args) throws JSONException {
String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
jsonObject.getJSONObject("users").getJSONObject("user").remove("age");
JSONObject marksJSONObject = new JSONObject();
marksJSONObject.put("marks",new int[]{23});
jsonObject.getJSONObject("users").put("newUser", marksJSONObject);
System.out.println(jsonObject);
}
OUTPUT:
{"users":{"newUser":{"marks":[23]},"report":{"sub":"eng","score":30},"user":{"name":"test1"}}}
String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
jsonObject.getJSONObject("users").getJSONObject("user").remove("age");
JSONObject newUser = new JSONObject();
newUser.put("marks", 32);
jsonObject.put("newUser", newUser);

Reading a json and csv dynamically with the same name

Reading first json with this name TestNameUS.json from the amazon S3Client directory and getting the sql from it and then hitting the db using the sql and matching the result with other Amazon S3 output directory containing the TestNameUS.csv with the same name as the name of the first json.
My code is below. It gives me the sql.How to read the directory dynamically with the name
public class ReadJsonFile {
public static void main(String[] args) {
// TODO Auto-generated method stub
JSONParser jsonParser = new JSONParser();
try {
Object obj = jsonParser.parse(new FileReader("./TestNameUS.json"));
// A JSON object. Key value pairs are unordered. JSONObject supports java.util.Map interface.
JSONObject jsonObject = (JSONObject) obj;
JSONArray query = (JSONArray) jsonObject.get("query");
String query1=null;
for(Object str : query) {
query1=(String)str;
}
System.out.println(query1);
System.out.println(query1.replaceAll("^\\('|\\'\\)$", ""));
} catch (Exception e) {
e.printStackTrace();
}
}
}

JSONObject with List to String to JsonNode

I convert JSONObject in string for parse it in JsonNode with jackson but i have a List in my JSONObject and when i parse it with a ObjectMapper i get this :
["{Property1 : value1, Property2 : value2}"]
And i can't call myJsonNodeObject.get(i).get("Property1") this is my problem.
I have tried to cast my List in JSONArray in my JSONObject but don't work.
resultAsJSONObject = new JSONObject();
resultAsJSONObject.put("Label", getMetricStatisticsResult.getLabel());
resultAsJSONObject.put("Datapoints", getMetricStatisticsResult.getDatapoints());
resultAsJSONObject.put("fromDate", fromDate.getTimeInMillis());
resultAsJSONObject.put("toDate", toDate.getTimeInMillis());
resultAsJSONObject.put("error", "");
resultAsString = resultAsJSONObject.toString();
mapper.readValue(resultAsString, MetricsData.class);
Assuming that you have a JSON string which you just want to change. Then you can use Jackson to parse it as a ObjecNode and then modify it. Here is an example:
public class JacksonModifyJson {
static final String JSON = "{\"name\":\"Bob\", \"age\":13}";
public static void main(String[] args) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
final ObjectNode jsonNode = mapper.readValue(JSON, ObjectNode.class);
jsonNode.put("url", "example.com");
System.out.println(mapper.writeValueAsString(jsonNode));
}
}
Output:
{"name":"Bob","age":13,"url":"example.com"}
THis method is really easy and works too
try {
JSONObject jsonObject = new JSONObject(THESTRINGHERE);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonArray;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
// System.out.println(listdata);
} catch (Exception e) {
System.out.println(e.getMessage());
}

Creating a JSON object

I am making a JSON request to server using Java. Here is the following parameters.
{method:'SearchBySearchConfiguration',params:[{{SearchCriteria:'%arriva',
IsAccountSearch:true,IsContactSearch:false,SearchByName:true,SearchByAddress:false
CRMTextValues:[], CRMCurrencyValues:[]}]}
I could do this way.
JSONObject json=new JSONObject();
json.put("method", "SearchBySearchConfiguration");
How do I add the rest of params, in name-value pair to JSON object?
Thanks in advance!
One way I can think of is using the org.json library. I wrote a sample to build part of your request object:
public static void main(String[] args) throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("method", "SearchBySearchConfiguration");
JSONArray jsonArray = new JSONArray();
JSONObject innerRecord = new JSONObject();
innerRecord.put("SearchCriteria", "%arriva");
innerRecord.put("IsAccountSearch", true);
jsonArray.put(innerRecord);
jsonObject.put("params",jsonArray);
System.out.println("jsonObject :"+jsonObject);
}
The output is :
jsonObject :{"method":"SearchBySearchConfiguration","params":[{"IsAccountSearch":true,"SearchCriteria":"%arriva"}]}
Another technique would be to build Java objects that resemble your request structure. You can then convert it into json using Jackson library's ObjectMapper class.
In both cases once you get the json string, you can directly write it into the request body.
JSONObject json=new JSONObject();
json.put("method", "SearchBySearchConfiguration");
JSONArray paramsArr = new JSONArray();
JSONObject arrobj = new JSONOject();
arrobj.put("SearchCriteria","%arriva");
arrobj.put("IsAccountSearch","true");
arrobj.put("IsContactSearch","false");
arrobj.put("SearchByName","true");
arrobj.put("SearchByAddress","false");
arrobj.put("CRMTextValues",new JSONArray());
arrobj.put("CRMCurrencyValues",new JSONArray());
paramsArr.put(arrobj);
json.put("params",paramsArr);
The you can create JSONArray and put that array in JSONObject
Its Better to use gson for this.
First you need to create classs with following members :
public class TestClass{
private String method;
private ParamClass params;
}
public class ParamClass{
private String SearchCriteria;
private boolean IsAccountSearch;
private boolean IsContactSearch;
private boolean SearchByName;
private boolean SearchByAddress;
private String[] CRMTextValues;
private String[] CRMCurrencyValues;
}
Usage :
Serializing :
Gson gson = new Gson();
String jsonString = gson.toJson(testClassObject);
Deserializing :
Gson gson = new Gson();
TestClass testClassObject = gson.fromJson(jsonString , TestClass.class);
See this below example, where a JSONArray is returned and then how i am converting it in JSONObject form...
public JSONArray go() throws IOException, JSONException {
JSONArray json = readJsonFromUrl("http://www.xxxxxxxx.com/AppData.aspx");
return json;
}
JSONArray jarr;
for(int i=0 ; i<jarr.length() ; i++){
JSONObject jobj = jarr.getJSONObject(i);
String mainText = new String();
String provText = new String();
String couText = new String();
try{
mainText = jobj.getString("Overview");
System.out.println(mainText);
}catch(Exception ex){}
try{
JSONObject jProv = jobj.getJSONObject("Provider");
provText = jProv.getString("Name");
System.out.println(provText);
}catch(Exception ex){}
try{
JSONObject jCou = jobj.getJSONObject("Counterparty");
couText = jCou.getString("Value");
System.out.println(couText);
}catch(Exception ex){}
Jackson is a very efficient to do JSON Parsing
See this link:
http://jackson.codehaus.org/
Gson is provided by google which is also a good way to handle JSON.
To add params, JSONArray is used.
Inside params, we use JSONObject to add data such as SearchByAddress, IsAccountSearch ..etc.
Reference http://www.mkyong.com/java/json-simple-example-read-and-write-json/
package com.test.json;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JsonSimpleExample {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("method", "SearchBySearchConfiguration");
JSONArray list = new JSONArray();
JSONObject innerObj = new JSONObject();
innerObj.put("SearchCriteria","%arriva" );
innerObj.put("IsAccountSearch",true);
innerObj.put("IsContactSearch",false);
innerObj.put("SearchByName",true);
innerObj.put("SearchByAddress",false);
innerObj.put("CRMTextValues",new JSONArray());
innerObj.put("CRMCurrencyValues",new JSONArray());
list.add(innerObj);
obj.put("params", list);
System.out.print(obj);
}
}

Java: Using GSon incorrectly? (null pointer exception)

I'm trying to get the hits of a google search from a string of the query.
public class Utils {
public static int googleHits(String query) throws IOException {
String googleAjax = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
String json = stringOfUrl(googleAjax + query);
JsonObject hits = new Gson().fromJson(json, JsonObject.class);
return hits.get("estimatedResultCount").getAsInt();
}
public static String stringOfUrl(String addr) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
URL url = new URL(addr);
IOUtils.copy(url.openStream(), output);
return output.toString();
}
public static void main(String[] args) throws URISyntaxException, IOException {
System.out.println(googleHits("odp"));
}
}
The following exception is thrown:
Exception in thread "main" java.lang.NullPointerException
at odp.compling.Utils.googleHits(Utils.java:48)
at odp.compling.Utils.main(Utils.java:59)
What am I doing incorrectly? Should I be defining an entire object for the Json return? That seems excessive, given that all I want to do is get one value.
For reference: the returned JSON structure.
Looking the returned JSON, it seems that you're asking for the estimatedResultsCount member of the wrong object. You're asking for hits.estimatedResultsCount, but you need hits.responseData.cursor.estimatedResultsCount. I'm not super familiar with Gson, but I think you should do something like:
return hits.get("responseData").get("cursor").get("estimatedResultsCount");
I tried this and it worked, using JSON and not GSON.
public static int googleHits(String query) throws IOException,
JSONException {
String googleAjax = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
URL searchURL = new URL(googleAjax + query);
URLConnection yc = searchURL.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String jin = in.readLine();
System.out.println(jin);
JSONObject jso = new JSONObject(jin);
JSONObject responseData = (JSONObject) jso.get("responseData");
JSONObject cursor = (JSONObject) responseData.get("cursor");
int count = cursor.getInt("estimatedResultCount");
return count;
}

Categories

Resources