I'm trying to create a json string of the following format in WP8
{"user": { "email": "abc#gmail.me", "password": "abc"}}
I have created { "email": "abc#gmail.me", "password": "abc*"} part like
string emailText = confirmEmailTbox.Text;
string passText = "password";
string pass = confirmPasswordPBox.Password;
Dictionary<string, string> jsonChild = new Dictionary<string, string>();
jsonChild.Add(emailText, email);
jsonChild.Add(passText, pass);
string jsonStringChild = JsonConvert.SerializeObject(jsonChild, Formatting.None);
But how do i put all this into the other object as in how do i add the "user" to the
jsonString
Edit: Both formats
{
"user": {
"email": "abc#gmail.me"
"password": "12345"
}
}
Leverage the anonymous objects available in C#:
var data = new { user = new { email=email, password = pass}};
string jsonStringChild = JsonConvert.SerializeObject(data);
Related
I have a local json file test.json
[
{
"id": 1,
"title": "test1"
},
{
"id": 2,
"title": "test2"
}
]
Class to read the json file
public static String getFileContent(String fileName){
String fileContent = "";
String filePath = "filePath";
try {
fileContent = new String(Files.readAllBytes(Paths.get(filePath)));
return fileContent;
}catch(Exception ex){
ex.printStackTrace();
}finally{
return fileContent;
}
}
I use rest assured to make the request and get same json response back
String fileContent= FileUtils.getFileContent("test.json");
when().
get("/testurl").
then().
body("", equalTo(fileContent));
This is what I got from local file
[\r\n {\r\n \"id\": 1,\r\n \"title\": \"test1\"\r\n },\r\n {\r\n \"id\": 2,\r\n \"title\": \"test2\"\r\n }\r\n]
This is the actual response:
[{id=1, title=test1}, {id=2, title=test2}]
Is there any better way to compare those two? I try to do something like fileContent.replaceAll("\\r\\n| |\"", ""); but it just removed all the space [{id:1,title:test1},{id:2,title:test2}]
Any help? Or any ways that just compare the content and ignore newline, space and double quote?
You can use any of the following methods
JsonPath :
String fileContent = FileUtils.getFileContent("test.json");
JsonPath expectedJson = new JsonPath(fileContent);
given().when().get("/testurl").then().body("", equalTo(expectedJson.getList("")));
Jackson :
String fileContent = FileUtils.getFileContent("test.json");
String def = given().when().get("/testurl").then().extract().asString();
ObjectMapper mapper = new ObjectMapper();
JsonNode expected = mapper.readTree(fileContent);
JsonNode actual = mapper.readTree(def);
Assert.assertEquals(actual,expected);
GSON :
String fileContent = FileUtils.getFileContent("test.json");
String def = given().when().get("/testurl").then().extract().asString();
JsonParser parser = new JsonParser();
JsonElement expected = parser.parse(fileContent);
JsonElement actual = parser.parse(def);
Assert.assertEquals(actual,expected);
I try to convert a json response to a list of persons.
This solution works but maybe there is a better solution to parse it.
(I can't change the response structure, but i can change the person if necessary)
Json Response:
{
"name1": {
"address": "abc",
"city": "xy"
},
"name2": {
"address": "abcdef",
"city": "xyzzzz"
}
}
My Person:
class Person{
name:string;
city:string;
address:string;
constructor(name: string, city: string, address: string) {
this.name = name;
this.city = city;
this.address = address;
}
}
My example implementation:
const value = JSON.parse(data);
const arr:Person[] = [];
for (var key in value) {
if (value.hasOwnProperty(key)) {
arr.push(new Person(key, value[key].city, value[key].address));
}
}
JSON.parse is dangerous, you must do with try catch
let value
try {
value = JSON.parse(data);
} catch (err) {
value = {};
}
const arr:Person[] = Object.keys(value)
.map(key => new Person(key, value[key].city, value[key].address));
JsonObjectBuilder builder = factory.createObjectBuilder().add("input", input);
JsonObject jsonData = builder.build();
String jsonDataString = jsonData.toString();
try {
OutputStream jsonStream = new FileOutputStream(jsonPath);
OutputStreamWriter jsonStreamWriter = new OutputStreamWriter(jsonStream);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String prettyOutput = gson.toJson(jsonData);
System.out.println(prettyOutput);
jsonStreamWriter.write(prettyOutput);
}
catch(Exception e) {}
The output I get is weird:
It adds '"value":' before every string value of a key.
My JSON data is something like this:
{
"input": {
"record0": {
"Active": "",
"Level": "",
"Name": "Pre-Session",
"Description": "",
"Record": "",
"Field": "",
"Std. Rule": "",
"Ext. Rule": "//Updated By: Sukanya Dasgupta On: 25-Jan-2016"
}
}
}
Not an expect but I think the problem is that public String toJson(Object src) loses type information :
This method should be used when the specified object is not a generic
type. This method uses Object.getClass() to get the type for the
specified object, but the getClass() loses the generic type
information because of the Type Erasure feature of Java.
I have a simple JSON
String jsonPayload = "{\"empid\": \"6\",\"empname\": \"Saurabh\",\"address\": \"home\"}";
jsonPayload.getBytes();
I created avro schema
{"namespace": "sample.namespace",
"type": "record",
"name": "Employee",
"fields": [
{"name": "empid", "type": "string"},
{"name": "empname", "type": "string"},
{"name": "address", "type": "string"}
]
}
When I try to compare them I get an error
Exception :
org.apache.avro.AvroRuntimeException: Malformed data. Length is negative: -62
at org.apache.avro.io.BinaryDecoder.doReadBytes(BinaryDecoder.java:336)
at org.apache.avro.io.BinaryDecoder.readString(BinaryDecoder.java:263)
at org.apache.avro.io.ResolvingDecoder.readString(ResolvingDecoder.java:201)
at org.apache.avro.generic.GenericDatumReader.readString(GenericDatumReader.java:430)
at org.apache.avro.generic.GenericDatumReader.readString(GenericDatumReader.java:422)
at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:180)
at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:152)
at org.apache.avro.generic.GenericDatumReader.readField(GenericDatumReader.java:240)
at org.apache.avro.generic.GenericDatumReader.readRecord(GenericDatumReader.java:230)
at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:174)
at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:152)
at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:144)
Looks like there is problem with String and Charsequence identification. Not able to identify exact problem
bytearraytojson converter method code
public String byteArrayToJson(byte[] avro, Schema schema) throws IOException {
boolean pretty = false;
GenericDatumReader<GenericRecord> reader = null;
JsonEncoder encoder = null;
ByteArrayOutputStream output = null;
try {
reader = new GenericDatumReader<GenericRecord>(schema);
InputStream input = new ByteArrayInputStream(avro);
output = new ByteArrayOutputStream();
DatumWriter<GenericRecord> writer = new GenericDatumWriter<GenericRecord>(schema);
encoder = EncoderFactory.get().jsonEncoder(schema, output, pretty);
Decoder decoder = DecoderFactory.get().binaryDecoder(input, null);
GenericRecord datum;
while (true) {
try {
datum = reader.read(null, decoder);
} catch (EOFException eofe) {
break;
}
writer.write(datum, encoder);
}
encoder.flush();
output.flush();
return new String(output.toByteArray());
} finally {
try {
if (output != null) output.close();
} catch (Exception e) {
}
}
}
Your problem is that the avro has the schema included.
If you want to read the avro you should to use other DataReader, DataFileReader
Here is a example that how read an avro in byte[] format with schema
Scala example:
def deserializeGenericWithSchema(message: Array[Byte]): Seq[GenericRecord] = {
val reader: DatumReader[GenericRecord] = new SpecificDatumReader[GenericRecord]()
val fileReader = new DataFileReader(new SeekableByteArrayInput(message),reader)
extractRec(fileReader,Seq.empty[GenericRecord])
}
#tailrec
def extractRec(fileReader: DataFileReader[GenericRecord], acc: Seq[GenericRecord]):Seq[GenericRecord] = {
if (fileReader.hasNext) {
val newElement = fileReader.next
extractRec(fileReader,acc :+ newElement)
} else {
acc
}
}
Java example:
public List<GenericRecord> deserializeGenericWithSchema(byte[] message) throws IOException {
List<GenericRecord>listOfRecords = new ArrayList<>();
DatumReader<GenericRecord> reader = new SpecificDatumReader<>();
DataFileReader<GenericRecord> fileReader =
new DataFileReader<>(new SeekableByteArrayInput(message),reader);
while (fileReader.hasNext()) {
listOfRecords.add(fileReader.next());
}
return listOfRecords;
}
PD: I have written the solution in scala and then I have traduced to Java, without testing. Maybe the Java solution is not completely perfect
you have to use morphline to convert json to avro.
Here is link.
http://cloudera.github.io/cdk/docs/current/cdk-morphlines/morphlinesReferenceGuide.html#/cdk-morphlines-avro
I am trying to parse this json in android and displaying the contents in list.
I am able to retrieve title,location and creator but dont know how to get inside des_update and retrieve text on '0'
[
{
"title": "my event ",
"location": "Chennai, Tamil Nadu, India",
"creator": "abc",
"des_update": {
"0": "this is my event with moderator"
}
},
{
"title": "my event 17",
"location": "pune",
"creator": "abc",
"des_update": {}
}
]
this is my parsing code I want to display data in alist
// convert json string to json array
JSONArray aJson = new JSONArray(sJson);
// create apps list
List<events> apps = new ArrayList<events>();
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
events app = new events();
app.setTitle(json.getString("title"));
app.setDate(json.getString("date"));
app.setLocation(json.getString("location"));
// add the app to apps list
apps.add(app);
...
}
you can use the following code:
JSONArray jsonArray = new JSONArray(json);
JSONObject object = jsonArray.getJSONObject(0);
JSONObject desObject = object.getJSONObject("des_update");
String data = desObject.getString("0");
System.out.println(data);
Here first you are loading your json string into JSONArray, and then you are taking one object from JSONArray instance. As des_update is an object with in the object you need to get that object calling getJSONObject() by passing your key and from there you can load the data that you want to use.
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String title = object.getString("title");
String location = object.getString("location");
String creator = object.getString("creator");
JSONObject des_update = object.getJSONObject("des_update");
String str = des_update.getString("0");
System.out.println("des_update-------" + str);
}