parse simple-JSONObject in JSONObject - java

i want to simple parse it to jsonObject .
the resone way is this i just want to manage order of the object
try {
{ JSONParser parser = new JSONParser();
ContainerFactory containerFactory = new ContainerFactory(){
public List creatArrayContainer() {
return new LinkedList(); }
public Map createObjectContainer() {
return new LinkedHashMap(); } };
json = (JSONObject)parser.parse(responce, containerFactory);
this is link where my question is
i m using simple jsonObject

Better use Jackson to simplify your work....
See this link:
http://jackson.codehaus.org/

Related

How to Update JSON value using Java

I have below json, i want to update each and every value of that json but sometimes only one value
{
"msgType": "NEW",
"code": "205",
"plid": "PLB52145",
}
I've already tried to update using below code
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
System.out.println(jsonObject);
long id =Long.valueOf((String) idNewObj.get("plid"));
System.out.println(plid);
idNewObj.put("plid",PL809809809);
System.out.println(jsonObject);
To make transformation/filtering of JSON files, I'd suggest to use stream/event-oriented parsing and generating rather than any object mapping. Just an example, which uses simple and lightweight JSON parser https://github.com/anatolygudkov/green-jelly :
import org.green.jelly.AppendableWriter;
import org.green.jelly.JsonEventPump;
import org.green.jelly.JsonParser;
import java.io.StringWriter;
import java.io.Writer;
public class UpdateMyJson {
private static final String jsonToUpdate = "{\n" +
"\"msgType\": \"NEW\",\n" +
"\"code\": \"205\",\n" +
"\"plid\": \"PLB52145\",\n" +
"}";
public static void main(String[] args) {
final StringWriter result = new StringWriter();
final JsonParser parser = new JsonParser();
parser.setListener(new MyJsonUpdater(result));
parser.parse(jsonToUpdate); // if you read a file with a buffer,
// call parse() several times part by part in a loop until EOF
parser.eoj(); // and then call .eoj()
System.out.println(result);
}
static class MyJsonUpdater extends JsonEventPump {
private boolean isPlid;
MyJsonUpdater(final Writer output) {
super(new AppendableWriter<>(output));
}
#Override
public boolean onObjectMember(final CharSequence name) {
isPlid = "plid".contentEquals(name);
return super.onObjectMember(name);
}
#Override
public boolean onStringValue(final CharSequence data) {
if (isPlid) {
if ("PLB52145".contentEquals(data)) {
return super.onStringValue("PL809809809");
}
}
return super.onStringValue(data);
}
}
}
Props:
the file/data doesn't require to be loaded entirely into memory, you can process megs/gigs with no problems
it works much more faster, especially for large files
it's easy to implement any custom type/rule of transformation with this pattern
Both of standard Gson and Jackson libs also provide tokenizers to work with JSON in streaming manner.
UPDATED: JsonEventPump used
You need to write the updated JSON into the file from where JSON was read. Also, I did not understand your variable assignment so I have updated that as well. Use below code:
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
System.out.println(jsonObject);
long id =Long.valueOf((String) idNewObj.get("plid"));
System.out.println(id);
jsonObject.put("plid",PL809809809);
System.out.println(jsonObject);
FileWriter writer = new FileWriter(filePath, false); //overwrites the content of file
writer.write(jsonObject.toString());
writer.close();

Java Object to JSON using GSON

I have an Object array which is a list of argument values a function could take. This could be any complex object.
I am trying to build a json out of the Object array using gson as below:
private JsonArray createArgsJsonArray(Object... argVals) {
JsonArray argsArray = new JsonArray();
Arrays.stream(argVals).forEach(arg -> argsArray.add(gson.toJson(arg)));
return argsArray;
}
This treats all the arg values as String.
It escapes the String args
"args":["\"STRING\"","1251996697","85"]
I prefer the following output:
"args":["STRING",1251996697,85]
Is there a way to achieve this using gson?
I used org.json, I was able to achieve the desired result, but it does not work for complex objects.
EDIT:
I applied the solution provided by #MichaƂ Ziober, but now how do I get back the object.
Gson gson = new Gson();
Object strObj = "'";
JsonObject fnObj = new JsonObject();
JsonObject fnObj2 = new JsonObject();
fnObj.add("response", gson.toJsonTree(strObj));
fnObj2.addProperty("response", gson.toJson(strObj));
System.out.println(gson.fromJson(fnObj.toString(),
Object.class)); --> prints {response='} //Not what I want!
System.out.println(gson.fromJson(fnObj2.toString(),
Object.class)); --> prints {response="\u0027"}
Use toJsonTree method:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import java.util.Date;
public class GsonApp {
public static void main(String[] args) {
GsonApp app = new GsonApp();
System.out.println(app.createArgsJsonArray("text", 1, 12.2D));
System.out.println(app.createArgsJsonArray(new Date(), new A(), new String[] {"A", "B"}));
}
private Gson gson = new GsonBuilder().create();
private JsonArray createArgsJsonArray(Object... argVals) {
JsonArray argsArray = new JsonArray();
for (Object arg : argVals) {
argsArray.add(gson.toJsonTree(arg));
}
return argsArray;
}
}
class A {
private int id = 12;
}
Above code prints:
["text",1,12.2]
["Sep 19, 2019 3:25:20 PM",{"id":12},["A","B"]]
If you want to end up with a String, just do:
private String createArgsJsonArray(Object... argVals) {
Gson gson = new Gson();
return gson.toJson(argVals);
}
If you wish to collect it back and alter just do:
Object[] o = new Gson().fromJson(argValsStr, Object[].class);
Try using setPrettyPrinting with DisableHtml escaping.
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(jsonArray.toString());
System.out.println( gson.toJson(je));

how to put json string into list in java

I'm getting a JSON array in string like
[ { "id":"ca.Primary_Diagnosis_Dt",
"field":"ca.Primary_Diagnosis_Dt",
"type":"date",
"input":"text",
"operator":"not_equal",
"value":"2016/06/07"
},
{ "id":"ca.Clinical_Stage",
"field":"ca.Clinical_Stage",
"type":"integer",
"input":"select",
"operator":"equal",
"value":"I"
}
]
i just want to save the value of id ,operator and value in LIST please help
Online : Working code
First create a class to store your values :
class Data{
String id;
String operator;
String value;
}
Then iterate over the json :
JSONArray jsonArr = new JSONArray("[JSON Stirng]");
List<Data> dataList = new ArrayList<>();
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
Data data = new Data();
data.id = jsonObj.getString("id");
data.operator = jsonObj.getString("operator");
data.value = jsonObj.getString("value");
dataList.add(data);
}
Now dataList has your data!
P.S. : Use getter/setters in Data class
JAR : http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm
Use any JSON parsor eg: GSON to create an arraylist of this particular json
Iterate the arraylist
Save it :)
You can do that with a JSon library such as org.glassfish.javax.json
In Maven use
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
</dependency>
Then read the string to a JsonArray:
JsonArray ja = Json.createReader(new StringReader(input)).readArray();
Then iterate over the list, map the objects to a new objects with just the values you need:
List<JsonObject> list = ja.stream()
.map(o -> (JsonObject) o)
.map(jo -> Json.createObjectBuilder()
.add("id", jo.getJsonString("id"))
.add("operator", jo.getJsonString("operator"))
.add("value", jo.getJsonString("value")).build())
.collect(Collectors.toList());
In case you could not use JsonObject as output, you may use a value object instead - just like Himanshu Tyagi proposed - and map the values to that object.
In your case, I think, the JSON should be parsed into a List<Map<String,String>>. This can be done using Jackson. Following is a method that converts a JSON string into List<Map<String,String>>:
public static List<Map<String, String>> toList(String json) throws IOException {
List<Map<String, String>> listObj;
ObjectMapper MAPPER = new ObjectMapper();
listObj = MAPPER.readValue(json, new TypeReference<ArrayList<HashMap<String, String>>>() {
});
return listObj;
}
If you have created a POJO class for it then you can use:
public static List<PojoClass> toList(String json) throws IOException {
List<PojoClass> listObj;
ObjectMapper MAPPER = new ObjectMapper();
listObj = MAPPER.readValue(json, new TypeReference<ArrayList<PojoClass>>() {
});
return listObj;
}
Maven dependency for Jackson:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>

How to extract data from this JSON?

I have the following JSON Array as a string like this,
String output = "[{\"Symbol\":\"AMZN\",\"Name\":\"Amazon.com Inc\",\"Exchange\":\"NASDAQ\"},{\"Symbol\":\"VXAZN\",\"Name\":\"CBOE Amazon VIX Index\",\"Exchange\":\"Market Data Express\"}]";
I want to parse it and make a string array like this,
array = {"AMZN Amazon.com Inc NASDAQ", "VXAZN CBOE Amazon VIX Index Market Data Express"};
I came up with the following code to parse the string into a JSON Array using the json-simple-1.1.1.jar library,
import org.json.simple.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class RESTclient {
public static void main(String[] args) {
String output = "[{\"Symbol\":\"AMZN\",\"Name\":\"Amazon.com Inc\",\"Exchange\":\"NASDAQ\"},{\"Symbol\":\"VXAZN\",\"Name\":\"CBOE Amazon VIX Index\",\"Exchange\":\"Market Data Express\"}]";
JSONParser parser = new JSONParser();
JSONArray jsonArray = null;
try {
jsonArray = (JSONArray) parser.parse(output);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(jsonArray);
}
}
This gives me the following OUTPUT,
[{"Name":"Amazon.com Inc","Exchange":"NASDAQ","Symbol":"AMZN"},{"Name":"CBOE Amazon VIX Index","Exchange":"Market Data Express","Symbol":"VXAZN"}]
Now after this, is there an elegant way to achieve my desired output?
You have to write extra code.
ArrayList<String> stringArray = new ArrayList<String>();
for (Iterator iterator = jsonArray.iterator(); iterator.hasNext();) {
JSONObject map = (JSONObject)iterator.next();
stringArray.add(map.get("Symbol")+" "+map.get("Name")+" "+map.get("Exchange"));
}
//stringArray is want you want
You can do it with Jackson like,
private ObjectMapper mapper = new ObjectMapper();
String[] outputArray = mapper.readValue(jsonString, String[].class);

Need help in constructing the JSON for the following

I have a problem at hand..
public class SomeClass{
List<Template> templateSettings;
}
public class Template{
String id;
List<TemplateChild> child;
}
public class TemplateChild{
String id;
String something;
}
at the ajax level i have
#ajax
public class saveSettings(SomeClass someclass){
List<Template> templateSettings = someclass.getTemplateSettings();
}
Its a bit complex , can someone help me in constructing the JSON for this, i am very new to javascript.. thanks..
Gson library will do that for you, Its pretty simple to use, here is the link
You can simply download the jar file and create the object like this
{ Gson gson = new Gson();
String convertedJson = gson.toJson(yourobject);}
And you are done.
Your JSON should look like
templetSettings= [{
template = {id="someId", childs=[{id="someId", something="something"},{id="someId2", something="something2"}]}},{
template = {//same as above},{
template = {//same as above}
]
Use JSONObject and JSONArray to create this kind of structure. Its pretty easy to use really
JSONArray templateSettings = new JSONArray();
for(//configure loop accordigly) {
JSONObject template = new JSONObject();
JSONArray childs = new JSONArray();
for (//Configure accordingly) {
JSONObject child = new JSONObject;
child.put("id", "someId");
child.put("something", "something");
childs.add(child);
}
template.put("id", "someId");
template.put("childs", childs);
templateSettings.add(template);
}
After this you only need to do is
out.write(templateSettings.toString());
And you are done
To do this on javaScript side loop accordingly and take help from this example
http://jsfiddle.net/AMISingh/636vN/

Categories