我做了一個小例子,它對我來說工作得很好。
域類:位置
package de.professional_webworkx.jackson.jacksondemo.domain;
import java.io.Serializable;
import java.util.Random;
public class Position implements Serializable {
private Long id;
private double lat;
private double lon;
protected Position() {}
public Position(final double lat, final double lon) {
this.id = generateId();
this.lat = lat;
this.lon = lon;
}
private Long generateId() {
Random random = new Random(System.currentTimeMillis());
return random.nextLong();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLon() {
return lon;
}
public void setLon(double lon) {
this.lon = lon;
}
}
如果你需要依賴於你的pom.xml
<dependencies>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.4</version>
<type>jar</type>
</dependency>
</dependencies>
這裏啓動應用程序
package de.professional_webworkx.jackson.jacksondemo;
import de.professional_webworkx.jackson.jacksondemo.domain.Person;
import de.professional_webworkx.jackson.jacksondemo.domain.Position;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.codehaus.jackson.map.ObjectMapper;
public class App {
public static final File FILENAME = new File("position.json");
public static final void main(String[] args) {
LocalDate birthday = LocalDate.of(1980, 1, 1);
Person person = new Person("Patrick", "Ott", "[email protected]");
Position position = new Position(48.113345, 11.273829);
try {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(FILENAME, position);
// here i read the position from the *.json file
Position readValue = mapper.readValue(FILENAME, Position.class);
System.out.println(readValue.getLat() + "N, " + readValue.getLon() + "E");
} catch (IOException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
結果是:
{"id":5799095657619062507,"lat":48.113345,"lon":11.273829}
JSON包含什麼,getAnyMethod是做什麼的?不要發佈僞代碼。準確告訴我們你在做什麼。 –
只需從文件本身用'InputStream'提供'ObjectMapper';你不需要閱讀字符串。特別是因爲你忘記指定編碼... – fge
我已經做了任何@fge說,即' ObjectMapper mapper = new ObjectMapper(); Position po = mapper.readValue(request.getInputStream(),Position.class); FileWriter writer = new FileWriter(「E://out.txt」); writer.write(po.getMobile()); write.write(po.getPassword()); writer.close(); '但它不適合我。 – sagar